'(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order,
"()" and "()[]{}" are all valid but "(]" and "([)]" are not.這一題的範例給得很爛...
他沒有把"({[]})" 例子給用出來
不過這一題的應用非常好,compiler的語法檢查,我想也可以用這種方式做
程式碼如下
class Solution {
public:
bool isValid(string s)
{
//分別利用set跟map 將 左半邊的符號 以及他對應右半邊的符號紀錄起來
unordered_set<char> leftset({'(', '{', '['});
unordered_map<char, char> closemap({{'(', ')'}, {'{', '}'}, {'[', ']'}});
//利用stack
stack<char> Stack;
for(int i = 0; i < s.size(); i++)
{
//如果是左邊的符號 就將它加入stack
if (leftset.count(s[i]) > 0)
{
Stack.push(s[i]);
}
else
{
//如果不是的話 就檢查stack是否已經空掉了或是它跟現在stack top的pair是不一樣的
if (Stack.empty() || s[i] != closemap[Stack.top()])
{
return false;
}
//通過後移除top
Stack.pop();
}
}
//最後檢查它還有沒有剩下的
return Stack.empty();
}
};
沒有留言 :
張貼留言