問題:
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.
大意:
給出一個(gè)只包含 '(', ')', '{', '}', '[' 和 ']' 的字符串,判斷它的輸入是否是有效的。
括號(hào)必須是以正確的順序關(guān)閉的, "()" 和 "()[]{}" 都是有效的,但是 "(]" 和 "([)]" 是無效的。
思路:
題目的要求說來也簡單,就是判斷括號(hào)是不是有效的,自己先用測試用例試了一下,括號(hào)中包含括號(hào)也是有效的。
其實(shí)無效的情況也就幾種,左括號(hào)匹配到了不一樣的右括號(hào)、左括號(hào)多了、右括號(hào)多了,我用一個(gè)數(shù)組記錄不同位置出現(xiàn)的括號(hào)的種類,出現(xiàn)新的右括號(hào)的時(shí)候判斷是否匹配到了正確的括號(hào),還要看是不是是多了的右括號(hào),最后看有沒有多出來的左括號(hào)。方法很笨,代碼也寫的很冗余,不過速度還可以。
代碼(Java):
public class Solution {
public boolean isValid(String s) {
int[] markArr = new int[s.length()];// 1表示(),2表示[],3表示{}
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '(') {
markArr[i] = 1;
} else if (arr[i] == ')') {
boolean hasMatched = false;
for (int j = i-1; j >= 0; j--) {
if (markArr[j] > 0 && markArr[j] != 1) return false;
else if (markArr[j] == 1) {
markArr[j] = 0;
hasMatched = true;
break;
}
}
if (!hasMatched) return false;
} else if (arr[i] == '[') {
markArr[i] = 2;
} else if (arr[i] == ']') {
boolean hasMatched = false;
for (int j = i-1; j >= 0; j--) {
if (markArr[j] > 0 && markArr[j] != 2) return false;
else if (markArr[j] == 2) {
markArr[j] = 0;
hasMatched = true;
break;
}
}
if (!hasMatched) return false;
} else if (arr[i] == '{') {
markArr[i] = 3;
} else if (arr[i] == '}') {
boolean hasMatched = false;
for (int j = i-1; j >= 0; j--) {
if (markArr[j] > 0 && markArr[j] != 3) return false;
else if (markArr[j] == 3) {
markArr[j] = 0;
hasMatched = true;
break;
}
}
if (!hasMatched) return false;
}
}
for (int i = 0; i < markArr.length; i++) {
if (markArr[i] > 0) return false;
}
return true;
}
}
他山之石:
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
// Iterate through string until empty
for(int i = 0; i<s.length(); i++) {
// Push any open parentheses onto stack
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
stack.push(s.charAt(i));
// Check stack for corresponding closing parentheses, false if not valid
else if(s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(')
stack.pop();
else if(s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[')
stack.pop();
else if(s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{')
stack.pop();
else
return false;
}
// return true if no open parentheses left in stack
return stack.empty();
}
}
這個(gè)做法用到了Stack棧這個(gè)類型,確實(shí)這道題很適合用棧來做,先進(jìn)后出,遇到左括號(hào)的時(shí)候放進(jìn)去,遇到右括號(hào)的時(shí)候從棧頂拿括號(hào)進(jìn)行匹配,匹配失敗就錯(cuò)了,全部匹配正確而且最后棧里沒東西了就對(duì)了。代碼簡潔多了。
合集:https://github.com/Cloudox/LeetCode-Record