Question
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.
看了題目以為“[{}]"這種是不合法的,結果這題這種string是合法的。
拿到題目之前已經知道這道題要用Stack來解,就直接上LinkedList了。
Solutions
以下是鄙人的渣解,思想就是用linkedList構成一個Stack結構的桶,然后每判斷一個字符
- 是“)”,"]","}",
- 桶為空, 扔進桶
- 不空,判斷桶的第一個字符是否為“)”,"]","}"對應的小伙伴
- 是,刪除小伙伴
- 不是, 返回false
- 不是“)”,"]","}, 扔進桶
public class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0)
return false;
LinkedList<Character> list = new LinkedList();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ')' || s.charAt(i) == ']' || s.charAt(i) == '}') {
if (list.size() > 0 && ((list.getFirst() - 'A' == s.charAt(i) - 1 - 'A')
|| (list.getFirst() - 'A' == s.charAt(i) - 2 - 'A'))) {
list.removeFirst();
} else if (list.size() > 0){
return false;
} else {
list.addFirst(s.charAt(i));
}
} else {
list.addFirst(s.charAt(i));
}
}
if (list.size() > 0) {
return false;
} else {
return true;
}
}
}
Points
- ASCII碼表
一開始以為{},[],()在表里都是連續的,結果代碼錯誤。實際上表里只有()是連續的,[]和{}都被第三者插足。
ascii01.png
- LeetCode Runtime
不是很懂LeetCode是怎么計算的,我相同的代碼,試了兩次一個1ms一個2ms,是不是再試一次就能達成0ms了?
屏幕快照 2016-03-16 上午10.48.08.png
屏幕快照 2016-03-16 上午10.48.22.png
TO DO
- Stack和LinkedList