LeetCode 32. 最长有效括号

最长有效括号

给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

方法一、栈

由于要存在配对,必然有')'存在,配对的长度为上一个')'到当前')'之间的距离,即为最长配对子串,因此,我们使用栈结构,存储上一次配对的')'所在的索引。栈存放**[最后一个没有被匹配的右括号的下标]**

复杂度分析

时间复杂度:O(n),n为字符串的长度,遍历一次

空间复杂度:O(n),n为字符串的长度,栈最多存储n个字符

Swift

swift 复制代码
func longestValidParentheses(_ s: String) -> Int {
        let cnt = s.count
        
        var res:Int = 0
        
        //栈,存放[最后一个没有被匹配的右括号的下标]
        let stack = Stack<Int>()
        stack.push(-1)//为了统一期间,假数据填充

        for i in 0..<cnt {
            let chara = s[s.index(s.startIndex, offsetBy: i)]
            if chara == "(" {
                stack.push(i)
            }else if(chara == ")") {
                let _ = stack.pop()
                
                if stack.count() == 0 {
                    stack.push(i)
                }else {
                    res = max(res, i - (stack.top() ?? 0))
                }
            }
        }
        return res
    }

OC

c 复制代码
- (NSInteger)longestValidParentheses:(NSString *)s {
    NSInteger res = 0;
    
    //存放[最后一个没有被匹配的右括号的下标]
    StackOC *stack = [[StackOC alloc] init];
    [stack push:@(-1)];//
    
    for (NSInteger i=0; i<s.length; i++) {
        unichar character = [s characterAtIndex:i];
        if (character == '(') {
            [stack push:@(i)];
        }else if(character == ')') {
            [stack pop];
            
            if ([stack empty]) {
                [stack push:@(i)];
            }else {
                //当前右括号索引减去上一个右括号的索引,表示最长串
                res = MAX(res, i-[[stack top] integerValue]);
            }
        }
    }
    
    return res;
}

方法二、双指针+双向遍历

思想:left对应 '('个数,right对应')'个数,当两者相等时,说明配对成功。

边界处理:当从左向右遍历时,right>left表示不连续了,要从0开始计数,因此将left和right置为0。

当从右向左遍历时,当left>right时表示不连续了,计数归0

复杂度分析

时间复杂度:O(n),n为字符串的长度,遍历一次

空间复杂度:O(1)

Swift

swift 复制代码
//双指针法,空间复杂度为O(1)
    func longestValidParentheses(_ s: String) -> Int {
        let cnt = s.count
        
        var left = 0, right = 0, maxLen = 0
        
        //从左向右找一次
        for i in 0..<cnt {
            let str = s[s.index(s.startIndex, offsetBy: i)]
            if str == "(" {
                left += 1
            }else if(str == ")") {
                right += 1
            }
            
            if left == right {
                maxLen = max(maxLen, 2*right)
            }else if(right > left) {
                left = 0
                right = 0
            }
        }
        
        //从右向左找一次
        left = 0; right = 0
        var j = cnt - 1
        while j > 0 {
            let str = s[s.index(s.startIndex, offsetBy: j)]
            
            if str == "(" {
                left += 1
            }else if(str == ")") {
                right += 1
            }
            
            if left == right {
                maxLen = max(maxLen, 2*right)
            }else if(left > right) {
                left = 0
                right = 0
            }
            
            j -= 1
        }
        
        return maxLen
    }

OC

c 复制代码
//双指针+左右遍历
- (NSInteger)longestValidParentheses:(NSString *)s {
    NSInteger left = 0, right = 0, maxLen = 0;
    
    //从左向右匹配一次
    for (NSInteger i=0; i<s.length; i++) {
        unichar charater = [s characterAtIndex:i];
        if (charater == '(') {
            left++;
        }else if(charater == ')') {
            right++;
        }
        
        if (left == right) {
            maxLen = MAX(maxLen, 2 * right);
        }else if(right > left) {
            left = right = 0;
        }
    }
    
    //从右向左匹配一次
    for (NSInteger i=s.length-1; i>0; i--) {
        unichar charater = [s characterAtIndex:i];
        if (charater == '(') {
            left++;
        }else if(charater == ')') {
            right++;
        }
        
        if (left == right) {
            maxLen = MAX(maxLen, 2*left);
        }else if(left > right) {
            left = right = 0;
        }
    }
    
    return maxLen;
}
相关推荐
牛客企业服务25 分钟前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
胡斌附体37 分钟前
linux测试端口是否可被外部访问
linux·运维·服务器·python·测试·端口测试·临时服务器
愚润求学1 小时前
【Linux】自旋锁和读写锁
linux·运维
大锦终1 小时前
【Linux】常用基本指令
linux·运维·服务器·centos
IT项目管理1 小时前
达梦数据库DMHS介绍及安装部署
linux·数据库
糖葫芦君1 小时前
Policy Gradient【强化学习的数学原理】
算法
知北游天1 小时前
Linux:多线程---深入互斥&&浅谈同步
linux·运维·服务器
Gappsong8741 小时前
【Linux学习】Linux安装并配置Redis
java·linux·运维·网络安全
try2find2 小时前
移动conda虚拟环境的安装目录
linux·运维·conda
码农101号2 小时前
Linux中容器文件操作和数据卷使用以及目录挂载
linux·运维·服务器