【英雄算法六月集训】Day13
剑指 Offer 31. 栈的压入、弹出序列
https://leetcode.cn/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/
两个下标变量(指针),一个指向pushed,一个指向popped
while遍历,pushed用指针push完,然后开始遍历popped,遇到栈顶元素相同的就出栈 pop,最后判断下i和j的大小 i是否等于pushed数组的大小,j 是否小于popped数组的大小
最后大小不相等则出栈顺序不正确
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int i=0,j=0;
Stack<Integer> stack = new Stack<Integer>();
while(i<pushed.length||j<popped.length){
if(i<pushed.length){
stack.push(pushed[i++]);
}
while(!stack.empty()&&stack.peek() == popped[j]){
stack.pop();
++j;
}
if(i==pushed.length){
if (j<popped.length) {
return false;
}
}
}
return true;
}
}
946. 验证栈序列
https://leetcode.cn/problems/validate-stack-sequences/
代码思路同 《剑指 Offer 31. 栈的压入、弹出序列》
856. 括号的分数
https://leetcode.cn/problems/score-of-parentheses/
class Solution {
public int scoreOfParentheses(String s) {
int i,cnt=0;
int n = s.length();
int sum=0;
for(i=0;i<n;++i){
char c= s.charAt(i);
if(c == '('){
if(cnt==0){
cnt=1;
}else{
cnt = cnt<<1;
}
}else if(c==')'){
if(s.charAt(i-1) == '('){
sum+=cnt;
}
cnt=cnt>>1;
}
}
return sum;
}
}
1190. 反转每对括号间的子串
class Solution {
int index;
public String dfs(String s,int start){
String ret="";
for(index = start;index <s.length();++index){
if(s.charAt(index) == '('){
String st = dfs(s,index+1);
st = reverse(st,0,st.length()-1);
ret+=st;
}else if(s.charAt(index) == ')'){
return ret;
}else{
ret+=s.charAt(index);
}
}
return ret;
}
public String reverse(String str,int start,int end){
StringBuffer s = new StringBuffer(str.length());
// 第一部分
s.append(str.substring(0, start));
// 第二部分
for (int i = end; i >= start; i--) {
s.append(str.charAt(i));
}
// 第三部分
s.append(str.substring(end + 1));
return s.toString();
}
public String reverseParentheses(String s) {
return dfs(s,0);
}
}