简单题,用stack可以直接搞定!
class Solution {
private boolean isValid(char m, char t){
return ((m == '(' && t == ')') || (m == '{' && t == '}') || (m == '[' && t == ']'));
}
public boolean isValid(String s) {
Stack<Character> stk = new Stack<>();
int len = s.length();
int i = 1;
stk.push(s.charAt(0));
while(i < len){
char t = s.charAt(i);
if(t == '(' || t == '{' || t == '['){
stk.push(t);
}else{
if(stk.empty()) return false;
char m = stk.pop();
if(!isValid(m, t)) return false;
}
++i;
}
return stk.empty();
}
}
之前Goldman Sachs考过一道很相似的,我用loop解决的…效率肉眼可见的低。虽然stack解决起来也不快的样子(见下图),但用StringBuilder肯定更快!我一定找时间学一下StringBuilder!
class Solution {
private String reverse(String a){
int len = a.length();
String res = "";
for(int i = len-1; i >= 0; --i){
res += a.charAt(i);
}
return res;
}
public String removeDuplicates(String s) {
Stack<Character> stk = new Stack<>();
int len = s.length();
for(int i = 0; i < len; ++i){
char t = s.charAt(i);
if(!stk.empty() && stk.peek() == t){
stk.pop();
}else{
stk.push(t);
}
}
String res = "";
while(!stk.empty()){
res += stk.pop();
}
return reverse(res);
}
}
由于Java语言确实不行,只能这么长…
我觉得存一个stack of Integer会好很多,就不用convert了。不过anyways,就这样吧。
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stk = new Stack<>();
int res = 0;
for(int i = 0; i < tokens.length; ++i){
if(tokens[i].equals("+")){
int a = Integer.parseInt(stk.pop());
int b = Integer.parseInt(stk.pop());
Integer tmp = new Integer(a+b);
stk.push(tmp.toString());
}else if(tokens[i].equals("-")){
int a = Integer.parseInt(stk.pop());
int b = Integer.parseInt(stk.pop());
Integer tmp = new Integer(b-a);
stk.push(tmp.toString());
}else if(tokens[i].equals("*")){
int a = Integer.parseInt(stk.pop());
int b = Integer.parseInt(stk.pop());
Integer tmp = new Integer(a*b);
stk.push(tmp.toString());
}else if(tokens[i].equals("/")){
int a = Integer.parseInt(stk.pop());
int b = Integer.parseInt(stk.pop());
Integer tmp = new Integer(b/a);
stk.push(tmp.toString());
}else{
stk.push(tokens[i]);
}
}
return Integer.parseInt(stk.pop());
}
}
今天题普遍很简单啊,看我下午如果有时间再来做一两道。
博客分享了LeetCode上几道简单题的解法。如Valid Parentheses可用栈解决;Remove All Adjacent Duplicates In String用循环效率低,用StringBuilder可能更快;Evaluate Reverse Polish Notation存一个Integer栈可避免转换。作者表示题较简单,下午有空再做。

被折叠的 条评论
为什么被折叠?



