題目:
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.
題意:給定一個字符串,裏面只包含'('
, ')'
, '{'
, '}'
, '['
and ']'
幾種字符,"()"
and "()[]{}"
幾種字符串都是合法的,而"(]"
and "([)]"
字符串都是非法的,所以現在給定一個字符串判定是否合法。
解題思路:
1.首先判斷字符串的長度,如果是奇數,直接返回false;
2.循環判斷相鄰字符是否爲一個匹配項:(1)如果相鄰字符匹配,即s[i]和s[i+1]是否匹配,若匹配則跳過這兩個字符,i=i+2;
(2)如果相鄰字符不匹配,則將第一個字符存儲s[i]到一個新的字符串tem中,i++;
3.循環判定tem,如果tem長度最後保持不變,則說明裏面字符不匹配,返回false,如果tem長度最後爲0,則表示全匹配上,返回true。
代碼: