給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
https://leetcode-cn.com/problems/valid-parentheses/
遇到左括號就入棧, 遇到右括號就出棧 , 看看右括號和pop出的左括號是否匹配,
如果匹配,繼續遍歷字符串 , 不匹配,就返回NO;
最後結束的時候,檢查棧中是否情況了,如果還有值說明,不匹配
#import "ViewController.h"
@interface ViewController ()
// 用數組模擬出一個棧
@property (nonatomic, strong) NSMutableArray *array;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 測試用例
NSString *str = @"({[]})";
NSString *str1 = @"]{[]})";
NSString *str2 = @"({[]})[]";
[self invalidDesripter:str];
[self invalidDesripter:str1];
[self invalidDesripter:str2];
[self invalidDesripter:@"{}({[]})[[]]"];
[self invalidDesripter:@"{"];
}
- (BOOL)invalidDesripter:(NSString *)descripter {
if (descripter.length == 0) {
return NO;
}
NSDictionary *despriterDic = @{@"(":@")",@"[":@"]", @"{":@"}"};
for (NSInteger i = 0 ; i < descripter.length; i++) {
NSString *subStr = [descripter substringWithRange:NSMakeRange(i, 1)];
if ([despriterDic.allKeys containsObject:subStr]) {
[self.array addObject:subStr];
}else {
NSString *value = self.array.lastObject;
[self.array removeLastObject];
if ([despriterDic[value] isEqualToString:subStr]) {
continue;
}else {
NSLog(@"%@ 不可以",descripter);
return NO;
}
}
}
// 判定這種情況,比如{(),數組中有值說明沒有成對出現
if (self.array.count == 0) {
NSLog(@"%@ 可以",descripter);
return YES;
}
NSLog(@"%@ 不可以",descripter);
return NO;
}
- (NSMutableArray *)array {
if (_array == nil) {
_array = [NSMutableArray array];
}
return _array;
}
@end