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.
- (BOOL)isValid:(NSString *)inputStr
{
//1
if (inputStr.length == 0 || inputStr.length%2 == 1)
{
return NO;
}
//2
DSStack *newStack = [[DSStack alloc] initWithSize:10];
for (int i =0 ; i<inputStr.length; i++)
{
//3
unichar tempChar = [inputStr characterAtIndex:i];
if (tempChar =='(' || tempChar =='{' || tempChar == '[')
{
[newStack push:[NSString stringWithCharacters:&tempChar length:1]];
}
//4
else
{
if (newStack && [self isPairLeftAndRight:[newStack peek] right:[NSString stringWithCharacters:&tempChar length:1]])
{
[newStack popLastObject];
}
else
{
return NO;
}
}
}
//5
return [newStack isEmpty];
}
代码思路描述:
如果输入字符串是空或者奇数则invalid。
创建一个新的stack。
遍历字符串把含有( { [ 字符放到栈里便于匹配。
如果栈顶字符和tempChar字符匹配则栈顶字符出栈,否则invalid。
匹配完毕如果stack是空则valid。
Time Complexity: O(n)
Space Complexity: O(n) ,由于借助stack存储
https://github.com/renmoqiqi/100-Days-Of-iOS-DataStructure-Algorithm/tree/master/Day03
本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/100tianiosshujujiegouyusuanfashizhan-day03-zhandesuanfashizhan-valid-parentheses.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:3 月 28, 2019 at 04:47 下午