題目
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
給定一個只包含 ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ , ‘]’這些字符的字符串,判斷該字符串是否有效。
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
輸入的字符串有效的判定方式是:左括號只能被相同類型的右括號關閉且左括號必須要被正確的順序來關閉。
Note that an empty string is also considered valid.
另外,空字符串也是有效的。
解題思路
不管哪種括號,必須只能被相同類型的括號關閉。換種角度來思考,那就是右括號只能和最近的和自己類型相同的左括號匹配。 這樣,我們再往下思考,只要把每次把最近放進去的括號匹配成功了那就是有效的字符串。我們從前往後遍歷字符串,然後選擇ArrayList來存儲當前位置的字符:如果當前字符是任意類型的左括號,那就是將當前字符添加到ArrayList中去;若果當前字符是任意類型的右括號,那就判斷它和ArrayList末尾的左括號是否匹配,如果匹配那就是把ArrayList末尾的字符刪除,如果不匹配那就說明返回false。
代碼
Java代碼如下:
public boolean isValid(String s) {
List<Character> list = new ArrayList<>();
//空字符串也是有效
if (s.length() == 0)
return true;
//如果一開始就是右括號那就是無效字符串
if (s.charAt(0) == ')' || s.charAt(0) == ']' || s.charAt(0) == '}')
return false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
list.add(s.charAt(i));
} else {
if (s.charAt(i) == ')') {
if (list.size()!=0&&list.get(list.size() - 1) == '(') {
list.remove(list.size() - 1);
} else {
return false;
}
}
else if (s.charAt(i) == ']') {
if (list.size()!=0&&list.get(list.size() - 1) == '[') {
list.remove(list.size() - 1);
} else {
return false;
}
}
else if (s.charAt(i) == '}') {
if (list.size()!=0&&list.get(list.size() - 1) == '{') {
list.remove(list.size() - 1);
} else {
return false;
}
}
}
}
//最後list是否全部匹配,全部匹配的話那麼list的大小就是0
if(list.size()!=0) return false;
return true;
}