1. 程式人生 > >LeetCode記錄之20——Valid Parentheses

LeetCode記錄之20——Valid Parentheses

{} 循環 i++ nth return urn term ket style

本題主要是找是否有匹配的字符串,因為還沒有復習到棧之類的知識點,只能還是采用暴力方法了,後期會補上更加優化的算法。我的思路就是先遍歷一遍找是否有匹配的符號,有的話就刪除,然後繼續遍歷,直至結束。

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.

給定一個字符串,只包含字符“(”、“””、“{”、“}”、“[”和“”),確定輸入字符串是否有效。
括號必須以正確的順序關閉,“()”和“()”{“}”都是有效的,但“()和[([ ] ] ] ]不是。


 1 public boolean isValid(String s){
 2         int length=s.length();
 3         boolean isDelete=false;
 4         if(length==0||length%2!=0)//判斷字符串是否為空或者無法匹配
 5             return
false; 6 while (length >0) { 7 for (int i = 0; i < length - 1; i++) { 8 if ((s.charAt(i) == ‘(‘ && s.charAt(i + 1) == ‘)‘) || (s.charAt(i) == ‘{‘ && s.charAt(i + 1) == ‘}‘) 9 || (s.charAt(i) == ‘[‘ && s.charAt(i + 1) == ‘]‘)) {
10 if(i+2!=length) 11 s = s.substring(0, i) + s.substring(i + 2, length);//非最後兩位字符串截取 12 else 13 s = s.substring(0, i);//最後兩位字符串截取 14 length -= 2;//字符串長度減2 15 isDelete=true; 16 i=0;//每次將基數歸零重新循環 17 } 18 else 19 isDelete=false;//如果循環一次沒有任何匹配直接返回false 20 } 21 if (!isDelete) 22 return false; 23 } 24 return true; 25 }

LeetCode記錄之20——Valid Parentheses