经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 编程经验 » 查看文章
LeetCode 20. Valid Parentheses
来源:cnblogs  作者:flowingfog  时间:2018/10/15 9:05:56  对本文有异议

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

  1. Input: "()"
  1. Output: true

Example 2:

  1. Input: "()[]{}"
  1. Output: true

Example 3:

  1. Input: "(]"
  1. Output: false

Example 4:

  1. Input: "([)]"
  1. Output: false

Example 5:

  1. Input: "{[]}"
  1. Output: true
  1.  
  1. package LeetCode;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Stack;
  5.  
  6. public class L20_ValidParentheses {
  7. public boolean isValid(String s) {
  8. int len=s.length();
  9. Stack<Character> stack=new Stack<Character>();
  10. if(len==0)
  11. return true;
  12. if(len%2!=0)
  13. return false;
  14. Map<Character,Character> map=new HashMap<Character,Character>();
  15. map.put('(',')');
  16. map.put('[',']');
  17. map.put('{','}');
  18. map.put(')',' ');
  19. map.put(']',' ');
  20. map.put('}',' ');
  21. //stack.push(s.charAt(0));
  22. for(int i=0;i<len;i++)
  23. {
  24. if (stack.empty())//栈为空
  25. stack.push(s.charAt(i));
  26. else if(s.charAt(i)!=map.get(stack.peek()))//或输入与栈顶不匹配
  27. stack.push(s.charAt(i));
  28. else
  29. stack.pop();
  30. }
  31. if(stack.empty())
  32. return true;
  33. else
  34. return false;
  35. }
  36.  
  37. public static void main(String[] args){
  38. L20_ValidParentheses l20=new L20_ValidParentheses();
  39. String test="([)]";
  40. boolean result=l20.isValid(test);
  41. System.out.println(result);
  42. }
  43. }

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号