1. 程式人生 > >Java&LeetCode 初入門——020. 有效的括號

Java&LeetCode 初入門——020. 有效的括號

Java&LeetCode 初入門——020. 有效的括號


文內程式碼全部採用JAVA語言。
個人認為本文的辦法雖然慢,但是非常好理解,是小白們的福音。

題目

給定一個只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字串,判斷字串是否有效。

有效字串需滿足:

  1. 左括號必須用相同型別的右括號閉合。
  2. 左括號必須以正確的順序閉合。左括號必須以正確的順序閉合。

注意空字串可被認為是有效字串。

測試用例

示例 1:

輸入: "()"
輸出: true

示例 2:

輸入: "()[]{}"
輸出: true

示例 3:

輸入: "(]"
輸出: false

示例 4:

輸入: "([)]"
輸出: false

示例 5:

輸入: "{[]}"
輸出: true

個人解法

看到這個題目的時候,沒有一下子想到解決辦法,因為需要考慮的情況實在太多了。但是在研究了測試用例之後,不難發現,不論多麼複雜的情況,如果是有效的括號,那麼總有兩個成套的括號是挨在一起的,也就是總存在"()","[]","{}“的子字串,我們如果將成套的括號一遍一遍的刪除,最終變成了”"空字串的話,說明是有效的 ,反之無效。

但是傻瓜辦法總是有點缺陷,就是時間很長。執行用時: 192 ms, 在Valid Parentheses的Java提交中擊敗了1.40% 的使用者。幾乎墊底。但程式碼簡單,通俗易懂,是小白們的福音了。

class Solution {
    public boolean isValid(String s) {
		while(s.indexOf("()")!=-1||s.indexOf("[]")!=-1||s.indexOf("{}")!=-1) {
		//如果字串裡存在"()","[]","{}",那麼就刪去。
			s=s.replace("()", "");
			s=s.replace
("[]", ""); s=s.replace("{}", ""); } //全部能全部刪除,說明有效。 if (s.length()==0) { return true; } else { return false; } } }

這麼垃圾的演算法如果用於編譯器那估計會慢到使用者想砸電腦,還是學習一下官方解法吧。

官方解法

方法


關於有效括號表示式的一個有趣屬性是有效表示式的子表示式也應該是有效表示式。(不是每個子表示式)例如
來自leedcode中文官網

此外,如果仔細檢視上述結構,顏色標識的單元格將標記開閉的括號對。整個表示式是有效的,而它的子表示式本身也是有效的。這為問題提供了一種遞迴結構。例如,考慮上圖中兩個綠色括號內的表示式。開括號位於索引 1,相應閉括號位於索引 6。

利用棧的功能,實現括號的消除,避免了迴圈查詢。

演算法

  1. 初始化棧 S。
  2. 一次處理表達式的每個括號。
  3. 如果遇到開括號,我們只需將其推到棧上即可。這意味著我們將稍後處理它,讓我們簡單地轉到前面的 子表示式。
  4. 如果我們遇到一個閉括號,那麼我們檢查棧頂的元素。如果棧頂的元素是一個 相同型別的
    左括號,那麼我們將它從棧中彈出並繼續處理。否則,這意味著表示式無效。
  5. 如果到最後我們剩下的棧中仍然有元素,那麼這意味著表示式無效。
class Solution {

  // Hash table that takes care of the mappings.
  private HashMap<Character, Character> mappings;

  // Initialize hash map with mappings. This simply makes the code easier to read.
  public Solution() {
    this.mappings = new HashMap<Character, Character>();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }

  public boolean isValid(String s) {

    // Initialize a stack to be used in the algorithm.
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      // If the current character is a closing bracket.
      if (this.mappings.containsKey(c)) {

        // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
        char topElement = stack.empty() ? '#' : stack.pop();

        // If the mapping for this bracket doesn't match the stack's top element, return false.
        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } else {
        // If it was an opening bracket, push to the stack.
        stack.push(c);
      }
    }

    // If the stack still contains elements, then it is an invalid expression.
    return stack.isEmpty();
  }
}

用上了棧之後果然快了很多。
附上自己寫的用棧的JAVA程式碼, 以及可以用於測試的主程式。

   public boolean isValid2(String s) {
		Map<Character, Character> map1=new HashMap<Character, Character>();
		map1.put(')','(');
		map1.put(']','[');
		map1.put('}','{');
		
		Stack<Character> st=new Stack<>();

		
		for (int i = 0; i < s.length(); i++) {
			char c =s.charAt(i);
			
			if (map1.containsKey(c)) {
				if(st.empty()==true || st.peek()!=map1.get(c)) {
					return false;	
				}
				else {
					st.pop();
				}
			}
			else {
				st.push(c);
			}
			
		}
		return st.empty();
	}
	public static void main(String[] args) {
		leedcode020 l20=new leedcode020();
		System.out.println(l20.isValid2("({})"));
	}