/**
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "([)]"
输出: false
*/
1.利用OC创建一个栈类:
#import "StackObject.h"
@interface StackObject()
@property (strong, nonatomic) NSMutableArray *stackArray;
@end
@implementation StackObject
- (NSMutableArray *)stackArray {
if (!_stackArray) {
_stackArray = [[NSMutableArray alloc] init];
}
return _stackArray;
}
- (void)push:(id)object {
[self.stackArray addObject:object];
}
- (void)pop {
if ([self isEmpty]) {
return;
}else {
[self.stackArray removeLastObject];
}
}
- (BOOL)isEmpty {
return !self.stackArray.count;
}
- (NSInteger)stackLength {
return self.stackArray.count;
}
- (void)enumerateObjectsFromBottom:(StackBlock)block {
[self.stackArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
block?block(obj):nil;
}];
}
- (void)enumerateObjectdFromTop:(StackBlock)block {
[self.stackArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
block?block(obj):nil;
}];
}
- (void)enumerateObjectsPopStack:(StackBlock)block {
__weak typeof(self) weakSelf = self;
for (NSInteger i = self.stackArray.count-1; i >= 0; i--) {
if (block) {
block(weakSelf.stackArray.lastObject);
[self.stackArray removeLastObject];
}
}
}
- (void)removeAllObjects {
[self.stackArray removeAllObjects];
}
- (id)topObject {
if ([self isEmpty]) {
return nil;
}else {
return [self.stackArray lastObject];
}
}
@end
2.继承栈类,创建方法如下:
- (BOOL)stringIsValid {
NSDictionary *dic = @{@"(":@")",@"[":@"]",@"{":@"}"};
NSString *inputStr = @"()[]{}";
NSLog(@"输入数据:%@",inputStr);
for (int i = 0; i < inputStr.length; i++) {
NSString *key = [NSString stringWithFormat:@"%c",[inputStr characterAtIndex:i]];
if ([[dic allKeys] containsObject:key]) {
[self push:key];
}else {
NSString *topElement = [self isEmpty]?@"*":[self topObject];
if ([[dic objectForKey:topElement] isEqualToString:key]) {
[self pop];
}else {
return false;
}
}
}
return self.isEmpty;
}
3.运行如下: