Leetcode Java_子序列

Yake1965 2022-01-07 20:10:51 阅读数:180

leetcode java_ java 序列

*402. 移掉 K 比特數字

Leetcode

class Solution {

public String removeKdigits(String num, int k) {

// 使用棧删除 x (<=k) 個元素
Deque<Character> deque = new LinkedList<Character>();
int n = num.length();
for (int i = 0; i < n; ++i) {

char digit = num.charAt(i);
while (!deque.isEmpty() && k > 0 && deque.peekLast() > digit) {

deque.pollLast();
k--;
}
deque.offerLast(digit);
}
// 如果 k > 0,繼續删除剩餘
for (int i = 0; i < k; ++i) {

deque.pollLast();
}
// 删除前導 0,然後轉成 String 返回
StringBuilder ret = new StringBuilder();
boolean leadingZero = true;
while (!deque.isEmpty()) {

char digit = deque.pollFirst();
if (leadingZero && digit == '0') continue;
leadingZero = false;
ret.append(digit);
}
return ret.length() == 0 ? "0" : ret.toString();
}
}
class Solution {

public String removeKdigits(String num, int k) {

if(k >= num.length()) return "0";
int n = num.length();
StringBuilder stack = new StringBuilder();
for(int i = 0;i < n;i++){

char c = num.charAt(i);
while (true){

int m = stack.length();
if (m > 0 && m + k > i && stack.charAt(m - 1) > c)
{

stack.deleteCharAt(m - 1);
}
else break;
}
if (stack.length() < n - k) stack.append(c);
}
String res = stack.toString();
int i = 0;
while(i < res.length()){

if(res.charAt(i) != '0') break;
i++;
}
return i == res.length() ? "0" : res.substring(i);
}
}
版权声明:本文为[Yake1965]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/01/202201072010507679.html