标签:
Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer. Make this new positive integers as small as possible.
N <= 240 and k <=N,
Example
Given an integer A = 178542, k = 4
return a string “12”
public class Solution {
/**
*@param A: A positive integer which has N digits, A is a string.
*@param k: Remove k digits.
*@return: A string
*/
public String DeleteDigits(String A, int k) {
String dp[][] = new String[A.length() - k][A.length()];
for (String[] dp1 : dp)
Arrays.fill(dp1, "");
for (int i = 0; i < A.length() - k; i++) {
for (int j = i; j < A.length(); j++) {
if (i == 0) {
String ss = A.substring(j, j + 1);
if (j == 0 || (j > 0 && ss.compareTo(dp[i][j - 1]) < 0))
// if (j == 0 || (j > 0 && !ss.equals("0") && ss.compareTo(dp[i][j - 1]) < 0))
dp[i][j] = ss;
else
dp[i][j] = dp[i][j - 1];
} else {
String x1 = dp[i - 1][j - 1] + A.substring(j, j + 1);
if (i == j || (j > i && dp[i][j - 1].compareTo(x1) > 0))
dp[i][j] = x1;
else
dp[i][j] = dp[i][j - 1];
}
}
}
String res = dp[A.length() - k - 1][A.length() - 1];
while (res.startsWith("0")) {
res = res.substring(1);
}
return res;
}
}
public String DeleteDigits(String A, int k) {
Stack<Integer> st = new Stack<Integer>();
int popCount = 0;
StringBuffer res = new StringBuffer();
for (int i = 0; i < A.length(); i++) {
int num = (int) (A.charAt(i) - ‘0‘);
if (st.isEmpty())
st.push(num);
else if (num >= st.peek()) {
st.push(num);
} else {
if (popCount < k) {
st.pop();
i--;
popCount++;
} else {
st.push(num);
}
}
}
while (popCount < k) {
st.pop();
popCount++;
}
while (!st.isEmpty()) {
res.insert(0, st.pop());
}
while (res.length() > 1 && res.charAt(0) == ‘0‘) {
res.deleteCharAt(0);
}
return res.toString();
}
标签:
原文地址:http://blog.csdn.net/wankunde/article/details/43792369