Given a string s of lower and upper case English letters.
A good string is a string which doesn’t have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
Input: s = “leEeetcode”
Output: “leetcode”
Explanation: In the first step, either you choose i = 1 or i = 2, both will result “leEeetcode” to be reduced to “leetcode”.
Example 2:
Input: s = “abBAcC”
Output: “”
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
“abBAcC” --> “aAcC” --> “cC” --> “”
“abBAcC” --> “abBA” --> “aA” --> “”
什么叫做good string, 就是没有同一字母但一个大写一个小写在相邻的位置上。
注意只是相邻,而不是一连串,比如leEeetcode, eEe是一连串的,但是只考虑从左到右相邻的2个,
只删掉左边的eE, 右边的e保留。
给出一个字符串,从左到右把相邻但不同大小写的字母删掉,返回删掉后的string。
思路:
因为只考虑从左到右,并只考虑相邻的2个字母。
遍历字母,加到res字符串作为结果,当res最右边的和当前字母是同一字母但不同大小写时,
把res最右边的删掉,当前的也不加进去。这就相当于删掉了2个相邻的字母。
因为只和res最右边的字母有关,考虑用stack.
遇到同一字母但不同大小写时,pop,否则push.
stack为空时也是push.
最后遍历stack,压入string, 注意stack遍历string的顺序是反向的。
public String makeGood(String s) {
Stack<Character> st = new Stack<>();
char[] chs = s.toCharArray();
StringBuilder sb = new StringBuilder();
st.push(chs[0]);
for(int i = 1; i < chs.length; i++) {
if(st.isEmpty() || Math.abs(st.peek() - chs[i]) != 32) { //同一字母大小写ascii差值为32
st.push(chs[i]);
} else {
st.pop();
}
}
while(!st.isEmpty()) {
sb.append(st.pop());
}
return sb.reverse().toString();
}
上面这种不是最高效的,因为面临了stack的push, pop, 和最后reverse操作。
可以用一个数组模拟stack, 只需要移动栈顶指针,
最后因为是数组,可以顺序遍历。
public String makeGood(String s) {
char[] chs = s.toCharArray();
char[] stack = new char[s.length()];
int top = -1;
for(char ch : chs) {
if(top < 0 || Math.abs(stack[top] - ch) != 32) {
//push
stack[++top] = ch;
} else {
//pop
top --;
}
}
return String.copyValueOf(stack, 0, top+1);
}
该博客探讨了一个字符串处理问题,定义了什么是好字符串并提供了算法实现。好字符串不包含相邻的大写和小写字母。给定一个字符串,通过删除相邻的不同大小写字母使其变为好字符串。文中给出了两种解决方案,一种使用栈,另一种利用数组,通过遍历和比较字符来优化字符串。最后,返回优化后的字符串。
277

被折叠的 条评论
为什么被折叠?



