20. 有效的括号
题目来源:leetcode 题库 20.有效的括号
思路
用栈(数组)储存未匹配成队的字符,
字符串以'\0'结尾
从头遍历字符串,
- 若当前字符与栈顶字符成对匹配,栈顶地址减一
- 若不成对,将当前字符放在栈顶,栈顶地址加一
遍历结束,若栈顶地址为0,说明所有字符都已成对匹配
代码
bool isValid(char * s){
int stack[10000] = {0};
int stackIndex = 1;
int i = 1;
bool Ret = true;
stack[0] = s[0];
while(s[i] != '\0')
{
switch (s[i])
{
case '(':
case '{':
case '[':
stack[stackIndex++] = s[i];
break;
case ')':
if((stackIndex > 0) && (stack[stackIndex - 1] == '('))
{
stackIndex--;
}
else
{
stack[stackIndex++] = s[i];
}
break;
case '}':
if((stackIndex > 0) && (stack[stackIndex - 1] == '{'))
{
stackIndex--;
}
else
{
stack[stackIndex++] = s[i];
}
break;
case ']':
if((stackIndex > 0) && (stack[stackIndex - 1] == '['))
{
stackIndex--;
}
else
{
stack[stackIndex++] = s[i];
}
break;
default:
break;
}
i++;
}
if(stackIndex != 0)
{
Ret = false;
}
return Ret;
}
1047. 删除字符串中的所有相邻重复项
思路
双指针,fast从字符串头+1遍历至尾,slow记录删除相邻重复项后剩余字符串的长度
若fast索引对应的字符与 删除相邻重复项后剩余字符串的最后一个字符重复,slow减一
若fast索引对应的字符与 删除相邻重复项后剩余字符串的最后一个字符不重复,将fast索引对应的字符赋值到slow对应的索引,slow加一
代码
char * removeDuplicates(char * s){
int slow = 1;
int fast = 1;
while(s[fast] != '\0')
{
if((slow > 0) && (s[slow - 1] == s[fast]))
{
slow--;
}
else
{
s[slow++] = s[fast];
}
fast++;
}
s[slow] = '\0';
return s;
}
150. 逆波兰表达式求值
给你一个字符串数组 tokens
,表示一个根据 逆波兰表示法 表示的算术表达式。
请你计算该表达式。返回一个表示表达式值的整数。
注意:
- 有效的算符为
'+'
、'-'
、'*'
和'/'
。 - 每个操作数(运算对象)都可以是一个整数或者另一个表达式。
- 两个整数之间的除法总是 向零截断 。
- 表达式中不含除零运算。
- 输入是一个根据逆波兰表示法表示的算术表达式。
- 答案及所有中间计算结果可以用 32 位 整数表示。
示例 1:
输入:tokens = ["2","1","+","3","*"] 输出:9 解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
示例 2:
输入:tokens = ["4","13","5","/","+"] 输出:6 解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
示例 3:
输入:tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] 输出:22 解释:该算式转化为常见的中缀算术表达式为: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22
思路
遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中
atoi能将为整型数值字符串转换为数值
遇到的坑:判断是否为操作符时,第一次使用下面代码判断的
/**
int evalRPN(char ** tokens, int tokensSize){
char* c;
*/
c = tokens[i];
if((*c == '+') || (*c == '-') || (*c == '*') || (*c == '/'))
但是遇到["10","6","9","3","+","-11","*","/","*","17","+","5","+"]用例中的"-11"时,会将"-11"判断为操作符
代码
bool isNumber(char *c)
{
bool Ret = false;
if(strlen(c) > 1)
{
Ret = true;
}
else if((*c == '+') || (*c == '-') || (*c == '*') || (*c == '/'))
{
Ret = false;
}
else
{
Ret = true;
}
return Ret;
}
int evalRPN(char ** tokens, int tokensSize){
int stack[10000] = {0};
int stackIndex = 0;
int i, first, second, temp;
char* c;
for(i = 0; i < tokensSize; i++)
{
c = tokens[i];
if(isNumber(c) == false)
{
second = stack[--stackIndex];
first = stack[--stackIndex];
switch (*c)
{
case '+':
temp = first + second;
break;
case '-':
temp = first - second;
break;
case '*':
temp = first * second;
break;
case '/':
temp = first / second;
break;
default:
break;
}
stack[stackIndex++] = temp;
}
else
{
stack[stackIndex++] = atoi(c);
}
}
return stack[0];
}