100天iOS数据结构与算法实战 Day03 – 栈的算法实战

题目描述

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.

思路描述

640 (2).gif

代码实现


 
  1. - (BOOL)isValid?NSString *)inputStr

  2. {

  3. //1

  4.    if (inputStr.length == 0 || inputStr.length%2 == 1)

  5.    {

  6.        return NO;

  7.    }

  8. //2

  9.    DSStack *newStack = [[DSStack alloc] initWithSize:10];

  10.  

  11.    for (int i =0 ; i<inputStr.length; i++)

  12.    {

  13.    //3

  14.        unichar tempChar = [inputStr characterAtIndex:i];

  15.        if (tempChar =='(' || tempChar =='{' || tempChar == '[')

  16.        {

  17.            [newStack push:[NSString stringWithCharacters:&tempChar length:1]];

  18.        }

  19.        //4

  20.        else

  21.        {

  22.            if (newStack && [self isPairLeftAndRight:[newStack peek] right:[NSString stringWithCharacters:&tempChar length:1]])

  23.            {

  24.                [newStack popLastObject];

  25.            }

  26.            else

  27.            {

  28.                return NO;

  29.            }

  30.        }

  31.    }

  32.  

  33.    //5

  34.    return [newStack isEmpty];

  35.  

  36. }

代码思路描述:

  1. 如果输入字符串是空或者奇数则invalid。

  2. 创建一个新的stack。

  3. 遍历字符串把含有( { [ 字符放到栈里便于匹配。

  4. 如果栈顶字符和tempChar字符匹配则栈顶字符出栈,否则invalid。

  5. 匹配完毕如果stack是空则valid。

复杂度估算

  • Time Complexity: O(n)

  • Space Complexity: O(n) ,由于借助stack存储

Demo

https://github.com/renmoqiqi/100-Days-Of-iOS-DataStructure-Algorithm/tree/master/Day03

 

  • 100天iOS数据结构与算法实战 Day01

  • 100天iOS数据结构与算法实战 Day02 – 栈

  • 交流群昵称:ios-Swift/Object C开发上架
    交流群号: 869685378   找ios马甲包开发者合作,有兴趣请添加Q 51259559
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值