- 基本思想:
对于读入的字符串,按顺序依次读取一个字符,如果该字符为左分隔符,则将其存入栈中。如果发现一个右分隔符,则与栈中弹出的元素相比较。如果二者相互匹配,则继续处理将标志match修改为true。反之中断处理并提示出错同时将标志macth修改为fasle。到达字符串末尾时检测栈是否为空与标志的状态得到匹配的最终结果
BOOL result = stack.isEmpty() && match
- 核心代码如下:
-(BOOL)match:(NSString *)str{
BOOL result = false;
if (str) {
if (!self.stack) {
self.stack = [[Stack alloc] initWithSize:[str length]];
}
for(int i = 0;i < [str length]; i++){
NSString *ch = [str substringWithRange:NSMakeRange(i,1)];
NSLog(@"34-----------:%@",ch);
if ([ch isEqualToString:@"["] || [ch isEqualToString:@"("] || [ch isEqualToString:@"{"]) {
[self.stack push:ch];
[self.stack test];
}else if([ch isEqualToString:@"]"] || [ch isEqualToString:@")"] || [ch isEqualToString:@"}"]){
if(![self.stack isEmpty]){
NSString* leftChar = (NSString*)[self.stack pop];
if ([ch isEqualToString:@")"] && [leftChar isEqualToString:@"("]) {
NSLog(@"41-------()匹配成功进行下一次匹配");
result = true;
continue;
}else if ([ch isEqualToString:@"]"] && [leftChar isEqualToString:@"["]) {
NSLog(@"44-------[]匹配成功进行下一次匹配");
result = true;
continue;
}else if ([ch isEqualToString:@"}"] && [leftChar isEqualToString:@"{"]) {
NSLog(@"44-------[]匹配成功进行下一次匹配");
result = true;
continue;
}else{
result = false;
NSLog(@"48-------匹配失败,待匹配的元素情况为:出栈元素:%@,遍历到的元素为:%@",leftChar,ch);
[self.stack test];
}
}else{
result = false;
NSLog(@"55-------匹配失败,多了字符:%@",ch);
}
}
}
if ([self.stack isEmpty] && result) {
NSLog(@"64-------匹配成功");
}else{
NSLog(@"66-------匹配失败");
}
}
return [self.stack isEmpty] && result;
}
- 测试接口:
[self.delimiterMatch match:@"(liu{09f[0]9-=)"];
-
实验失败例子:
*实验成功例子:
[self.delimiterMatch match:@"(liu{09f[0]9-}=)"];