首页 > 代码库 > [Leetcode] Valid Parentheses
[Leetcode] Valid Parentheses
Given a string containing just the characters ‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
and ‘]‘
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
Solution:
1 public class Solution { 2 public boolean isValid(String s) { 3 if (s == null || s.length() == 0) 4 return true; 5 if (s.length() == 1) 6 return false; 7 int N = s.length(); 8 int i = 0; 9 Stack<Character> myStack = new Stack<Character>();10 while (i < N) {11 char temp = s.charAt(i);12 if (temp == ‘(‘ || temp == ‘{‘ || temp == ‘[‘) {13 myStack.push(temp);14 i++;15 } else {16 if (!myStack.isEmpty()) {17 char t = myStack.pop();18 if (((t == ‘(‘) && (temp == ‘)‘))19 || ((t == ‘{‘) && (temp == ‘}‘))20 || ((t == ‘[‘) && (temp == ‘]‘))) {21 i++;22 } else {23 return false;24 }25 } else {26 return false;27 }28 }29 }30 if(myStack.isEmpty())31 return true;32 else33 return false;34 }35 }
我的代码风格太差了,贴一下大神的代码:
1 public class Solution { 2 public boolean isValid(String s) { 3 if (s == null) 4 return false; 5 Stack st = new Stack(); 6 for (int i = 0; i < s.length(); i++) { 7 if(s.charAt(i)==‘]‘||s.charAt(i)==‘)‘||s.charAt(i)==‘}‘){ 8 if(st.empty()) 9 return false;10 else{11 char c= st.pop().toString().charAt(0);12 if(!((c==‘(‘&&s.charAt(i)==‘)‘)||(c==‘[‘&&s.charAt(i)==‘]‘)||(c==‘{‘&&s.charAt(i)==‘}‘))){13 return false;14 } 15 }16 }else{17 st.push(s.charAt(i));18 }19 }20 return st.empty();21 }22 }
[Leetcode] Valid Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。