20. 有效的括号
题目链接:. - 力扣(LeetCode)
解题思路:如果为左边的符号,则进栈,如果为右边的符号,则与栈顶元素进行比对,如果匹配,则出栈,不匹配,返回false;如果最终栈中有剩余元素,说明有未匹配的。
时间复杂度:O(n) 空间复杂度:O(n)
C:
int notMatch(char par, char* stack, int stackTop) {
switch(par) {
case ']':
return stack[stackTop - 1] != '[';
case ')':
return stack[stackTop - 1] != '(';
case '}':
return stack[stackTop - 1] != '{';
}
return 0;
}
bool isValid(char* s) {
int strLen = strlen(s);
char stack[5000];
int stackTop = 0;
int i;
for(i = 0; i < strLen; i++) {
char tempChar = s[i];
if(tempChar == '(' || tempChar == '[' || tempChar == '{')
stack[stackTop++] = tempChar;
else if(stackTop == 0 || notMatch(tempChar, stack, stackTop))
return false;
else
stackTop--;
}
return !stackTop;
}
java:deque是一个双端队列,仅对其一端进行操作可以实现栈,push、poll、peek都是在队头进行操作
class Solution {
public boolean isValid(String s) {
Deque<Character> deque = new LinkedList<>();
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (ch == '(') {
deque.push(')');
}else if (ch == '{') {
deque.push('}');
}else if (ch == '[') {
deque.push(']');
} else if (deque.isEmpty() || deque.peek() != ch) {
return false;
}else {
deque.poll();
}
}
return deque.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
题目链接:. - 力扣(LeetCode)
解题思路:因为最多只有两个重复的,所以和上一个元素比对即可,如果重复,将上一个元素出栈
时间复杂度:O(n) 空间复杂度:O(1)
C:
char* removeDuplicates(char* s) {
int strLength = strlen(s);
char* stack = (char*)malloc(sizeof(char) * strLength + 1);
int stackTop = 0;
int index = 0;
while(index < strLength) {
char letter = s[index++];
if(stackTop > 0 && letter == stack[stackTop - 1])
stackTop--;
else
stack[stackTop++] = letter;
}
stack[stackTop] = '\0';
return stack;
}
java:
class Solution {
public String removeDuplicates(String s) {
StringBuffer res = new StringBuffer();
int top = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (top >= 0 && res.charAt(top) == c) {
res.deleteCharAt(top);
top--;
} else {
res.append(c);
top++;
}
}
return res.toString();
}
}