目录
20 有效的括号
创建一个栈stack,遍历字符串s。
如果字符为左括号则将右括号入栈。
如果字符为右括号,但栈为空,说明没有与之配对的左括号,则该字符串无效;如果字符为右括号但与栈顶元素不一致,则该字符串无效。
如果字符与栈顶元素一致,则栈顶元素出栈。
遍历结束后查看stack是否为空,如果为空则字符串s有效。
class Solution {
public boolean isValid(String s) {
if(s.length() % 2 == 1)return false;
Stack<Character>stack = new Stack<>();
for(int i = 0;i < s.length();i++){
char ch = s.charAt(i);
if(ch == '(')stack.push(')');
else if(ch == '[')stack.push(']');
else if(ch == '{')stack.push('}');
else if(stack.isEmpty() || ch != stack.peek()){
return false;
}else{
stack.pop();
}
}
return stack.isEmpty();
}
}
时间复杂度O(n),空间复杂度O(n)。
1047 删除字符串中的所有相邻重复项
方法一
class Solution {
public String removeDuplicates(String s) {
Stack<Character>stack = new Stack<>();
for(int i = 0;i < s.length();i++){
char ch = s.charAt(i);
if(!stack.isEmpty() && stack.peek() == ch)stack.pop();
else stack.push(ch);
}
String res = "";
while(!stack.isEmpty()){//由于栈的特性,需要反转
res = stack.pop() + res;
}
return res;
}
}
时间复杂度O(n)
空间复杂度O(n)
方法二
直接将字符串作为栈,省去了将栈转换为字符串的操作
class Solution {
public String removeDuplicates(String s) {
StringBuffer res = new StringBuffer();
int idx = -1;
for(int i = 0;i < s.length();i++){
char ch = s.charAt(i);
if(idx >= 0 && res.charAt(idx) == ch){
res.deleteCharAt(idx);
idx--;
}
else{
idx++;
res.append(ch);
}
}
return res.toString();
}
}
时间复杂度O(n)
空间复杂度O(n)
方法三
通过快慢指针的方式解题
class Solution {
public String removeDuplicates(String s) {
char arr[] = s.toCharArray();
int j = 0;//定义慢指针
for(int i = 0;i < arr.length;i++){
arr[j] = arr[i];
if(j >= 1 && arr[j] == arr[j - 1]){
j--;
}else{
j++;
}
}
return new String(arr,0,j);
}
}
时间复杂度O(n)
空间复杂度O(n)
150 逆波兰表达式求值
创建一个栈。
遇到运算符,则将取出栈顶的两个数字进行运算,运算结果入栈。
遇到数字,则直接入栈。
最后返回栈顶的数字。
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer>stack = new Stack<>();//注意<>中为Integer不是String
for(String s : tokens){
if("+".equals(s)){//不能使用==判断字符串是否相等
stack.push(stack.pop() + stack.pop());
}else if("-".equals(s)){// -需要进行特殊处理
int temp1 = stack.pop();//减数
int temp2 = stack.pop();//被减数
stack.push(temp2 - temp1);
}else if("*".equals(s)){
stack.push(stack.pop() * stack.pop());
}else if("/".equals(s)){// /需要进行特殊处理
int temp1 = stack.pop();//除数
int temp2 = stack.pop();//被除数
stack.push(temp2 / temp1);
}else{
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}
时间复杂度O(n)
空间复杂度O(n)