1. 程式人生 > >LeetCode 一題多解

LeetCode 一題多解

1. 括號匹配

  • 堆疊版:

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            para_map = {')':'(', ']':'[', '}':'{'}
            for c in s:
                if c not in para_map:
                    stack.append(c)
                elif not stack or stack.pop() != para_map.get(c):
                    return False
            return not stack
    
  • 字串處理版:

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            length = len(s)
            s = s.replace('()', '').replace('[]', '').replace('{}', '')
            while len(s) != length:
                length = len(s)
                s = s.replace('()', '').replace('[]', '').replace('{}', '')
            return length == 0
    

    使用 Java 的 do while 語句,形式上將更為簡潔:

    class Solution {
        public boolean isValid(String s) {
            int length;
            do {
                length = s.length();
                s = s.replace("()", "").replace("[]", "").replace("{}", "");
            } while (s.length() != length);
            return length == 0;
        }
    }