1750. 删除字符串两端相同字符后的最短长度
题目链接
【题目】
给你一个只包含字符 ‘a’,‘b’ 和 ‘c’ 的字符串 s ,你可以执行下面这个操作(5 个步骤)任意次:
选择字符串 s 一个 非空 的前缀,这个前缀的所有字符都相同。
选择字符串 s 一个 非空 的后缀,这个后缀的所有字符都相同。
前缀和后缀在字符串中任意位置都不能有交集。
前缀和后缀包含的所有字符都要相同。
同时删除前缀和后缀。
请你返回对字符串 s 执行上面操作任意次以后(可能 0 次),能得到的 最短长度 。
【思路】
经典的双指针。
【代码】
class Solution {
public int minimumLength(String s) {
int l = 0, r = s.length()-1;
while(l<r) {
if(s.charAt(l)!=s.charAt(r)) break;
while((l+1)<r&&s.charAt(l+1)==s.charAt(l)) l++;
while(l<(r-1)&&s.charAt(r-1)==s.charAt(r)) r--;
l++;r--;
}
return r-l+1;
}
}
面试题16.26.计算器
题目链接
【题目】
给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。
表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
【思路】
栈、队列的思想,遍历即可。
【代码】
class Solution {
public int calculate(String s) {
s = s.replaceAll(" ","");
Deque<Integer> q = new ArrayDeque<>();
char flag = '+';
int num = 0;
for(int i=0; i<s.length(); i++){
if(Character.isDigit(s.charAt(i))){
num = num*10 + (s.charAt(i) - '0');
}
if(!Character.isDigit(s.charAt(i)) || i == s.length()-1){
switch(flag){
case '+': q.push(num);break;
case '-': q.push(-num);break;
case '*': q.push(q.pop()*num);break;
case '/': q.push(q.pop()/num);break;
}
flag = s.charAt(i);
num = 0;
}
}
while(!q.isEmpty()){
num += q.pop();
}
return num;
}
}
//用栈做的,很慢
class Solution {
public int calculate(String s) {
s = s.replace(" ","");
Stack<Integer> numS = new Stack<>();
StringBuilder n = new StringBuilder("");
for(int i=0;i<s.length();i++) {
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9') {
n.append(s.charAt(i++));
}
if(n.length()>0&&!"".equals(n)) {
Integer num = Integer.parseInt(n.toString());
numS.push(num);
n = new StringBuilder("");
}
if(i==s.length())break;
char c = s.charAt(i);
if(c=='*'||c=='/') {
i++;
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9') {
n.append(s.charAt(i++));
}i--;
Integer num = Integer.parseInt(n.toString());
n = new StringBuilder("");
num = c=='*'?num*numS.pop():numS.pop()/num;
numS.push(num);
}else if(c=='-'){
i++;
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9') {
n.append(s.charAt(i++));
}i--;
Integer num = Integer.parseInt(n.toString());
n = new StringBuilder("");
numS.push(-num);
}
}
Integer ans = 0;
while(!numS.isEmpty()) {
ans+=numS.pop();
}
return ans;
}
}