面试题-字符对检查

面试题:字符串中包含{}[]()三对字符串,当输入时错位或少输多输都为格式错位。比如:{[]}()格式正确,而{[}()]格式错误。

应用栈来检查,遇到左括号就入栈,遇到右括号就把栈顶的左括号出栈。当字符串扫描完毕后,如果栈内元素为空,则说明括号匹配无误。如果完毕后栈内还有元素,则说明左括号多了;如果进行出栈操作时,栈内已经是空的了,说明右括号多了或者右括号之前没有左括号

这里直接用NSMutableArray充当零时的Stacks容器.实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
- (BOOL) checkPairString:(NSString *) string {

for (NSInteger i = 0; i<string.length ; i++) {
char str = [string characterAtIndex:i];
switch (str) {
case '[':
case '{':
case '(':
[self.stackArray addObject:[NSString stringWithFormat:@"%c",str]];
break;
case ']':
if (self.stackArray.count > 0 && [[self.stackArray lastObject] isEqualToString:@"["]){
[self.stackArray removeLastObject];

}else{
return NO;
}

break;
case '}':
if (self.stackArray.count > 0 && [[self.stackArray lastObject] isEqualToString:@ "{"]){
[self.stackArray removeLastObject];

}else{
return NO;
}

break;
case ')':
if (self.stackArray.count > 0 && [[self.stackArray lastObject] isEqualToString:@ "("]){
[self.stackArray removeLastObject];

}else{
return NO;
}

break;

default:
break;
}

}
if (self.stackArray.count == 0) {
return YES;
}
return NO;
}

测试代码

1
2
3
4
5
6
BOOL bo1 = [self checkPairString:@"{}[]()"];
BOOL bo2 = [self checkPairString:@"{[}[]()"];
BOOL bo3 = [self checkPairString:@"{}[](])[}"];
NSLog(@"%@",@(bo1));
NSLog(@"%@",@(bo2));
NSLog(@"%@",@(bo3));

输出结果

1
2
3
2018-08-01 19:26:06.514245+0800 DemoDemo[5837:852574] 1
2018-08-01 19:26:06.514453+0800 Demo[5837:852574] 0
2018-08-01 19:26:06.514568+0800 Demo[5837:852574] 0