记录刷力扣时遇到的一些技巧(栈与队列)
简单的逆波兰表达式
计算器无括号有乘除后缀表达式
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stk = new Stack<Integer>();
for(String token : tokens){
if(token.equals("+")) stk.push(stk.pop()+stk.pop());
else if(token.equals("-")) stk.push(-stk.pop()+stk.pop());
else if(token.equals("*")) stk.push(stk.pop()*stk.pop());
else if(token.equals("/"))
{
int a=stk.pop(),b=stk.pop();
stk.push(b/a);
}
else stk.push(Integer.parseInt(token));
}
return stk.pop();
}
}
[227]给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
计算器无括号有乘除
class Solution {
public int calculate(String s) {
// 保存上一个符号,初始为 +
char sign = '+';
Stack<Integer> numStack = new Stack<>();
// 保存当前数字,如:12是两个字符,需要进位累加
int num = 0;
int result = 0;
for(int i = 0; i < s.length(); i++){
char cur = s.charAt(i);
if(cur >= '0'){
// 记录当前数字。先减,防溢出
num = num*10 - '0' + cur;
}
if((cur < '0' && cur !=' ' )|| i == s.length()-1){
// 判断上一个符号是什么
switch(sign){
// 当前符号前的数字直接压栈
case '+': numStack.push(num);break;
// 当前符号前的数字取反压栈
case '-': numStack.push(-num);break;
// 数字栈栈顶数字出栈,与当前符号前的数字相乘,结果值压栈
case '*': numStack.push(numStack.pop()*num);break;
// 数字栈栈顶数字出栈,除于当前符号前的数字,结果值压栈
case '/': numStack.push(numStack.pop()/num);break;
}
// 记录当前符号
sign = cur;
// 数字清零
num = 0;
}
}
// 将栈内剩余数字累加,即为结果
while(!numStack.isEmpty()){
result += numStack.pop();
}
return result;
}
}
计算器有括号无乘除
class Solution {
public int calculate(String s) {
Stack<Integer> stack =new Stack<Integer>();
int sign = 1,res = 0;
int length = s.length();
for(int i=0;i<length;i++){
char ch = s.charAt(i);
if(Character.isDigit(ch)){
int cur = ch - '0';
//多位数字
while(i+1<length&& Character.isDigit(s.charAt(i+1))){
i++;
int a =s.charAt(i)-'0';
cur = cur*10 + a ;
}
res += sign*cur;
}
else if(ch == '+') sign=1;
else if(ch == '-') sign=-1;
//存历史数据
else if(ch == '(') {
stack.push(res);
stack.push(sign);
res = 0;
sign = 1;
}
else if(ch == ')') res = stack.pop() * res + stack.pop();
}
return res;
}
}
有括号有乘除
public int solve (String s) {
// write code here
Stack<Integer> stack = new Stack<>();
int number = 0;
int sum = 0;
char sign = '+';
char[] c = s.toCharArray();
int n = s.length();
for (int i = 0; i < n; i++)
{
char ele = c[i];
//process the numerical situation
if (Character.isDigit(ele))
{
number = number * 10 + ele - '0';
}
//process the () situation
if (ele == '(')
{
int j = i + 1;
int counterPar = 1;
String subPar = "";
//extract the most outer group and recursevely preocess
while (counterPar > 0)
{
if (c[j] == '(')
{
counterPar++;
}
if (c[j] == ')')
{
counterPar--;
}
j++;
}
subPar = s.substring(i + 1, j);
number=solve(subPar);
i = j-1;
}
//real work block
if (ele != ' ' && !Character.isDigit(ele) || i == n - 1)
{
if (sign == '+')
{
stack.push(number);
}
else if (sign == '-')
{
stack.push(-1 * number);
}
else if (sign == '*')
{
stack.push(stack.pop() * number);
}
else if (sign == '/')
{
stack.push(stack.pop() / number);
}
//change the sign and number
number = 0;
sign = ele;
}
}
while (!stack.isEmpty())
{
sum+=stack.pop();
}
return sum;
}
[32]给你一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
class Solution {
public int longestValidParentheses(String s) {
int max=0;//存放最大的长度
int len=s.length();//字符串长度
Stack<Integer> stack=new Stack<Integer>();//暂存字符
stack.push(-1);//初始化栈底
for(int i=0;i<len;i++) {//遍历字符串
if(s.charAt(i)=='(')//字符串存在(
stack.push(i);//下标入栈
else {//只有右边
stack.pop();//下标出栈
if(stack.isEmpty()) {//出栈以后,栈为空
stack.push(i);//让当前下标进栈
}else {//不为空,就计算长度差值
max=Math.max(max, i-stack.peek());//选出最长的长度
}
}
}
return max;
}
}
给出一个仅包含字符’(’,’)’,’{’,’}’,’[‘和’]’,的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()“和”()[]{}“都是合法的括号序列,但”(]“和”([)]"不合法。
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
//使用foreach循环
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}