给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
提示:
1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成
c++:
class Solution {
public:
bool isValid(string s) {
size_t found;
while ((found = s.find("{}")) != string::npos || (found = s.find("()")) != string::npos || (found = s.find("[]")) != string::npos) {
s.erase(found, 2);
}
return s.empty();
}
};
注释:
1.find()函数会在字符串中查找第一次出现子字符串的位置,并返回该位置的索引值
2.string::npos是一个常量值,表示无法找到子字符串或字符的位置。它的值是std::string 类中的一个静态成员,通常被用于判断某个子字符串是否存在或进行查找操作的结果是否成功。
python:
class Solution:
def isValid(self, s):
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''