Problem #27 [Easy]

This problem was asked by Facebook.

Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).

For example, given the string “([])”, you should return true.

Given the string “([)]” or “((()”, you should return false.
首先很容易想到用栈去解决,空间复杂度为O(N), 时间复杂度为O(N), N为括号字符串的长度。

def balanced_brackets(str):
    bracktes = {')': '(', ']': '[','}':'{'}
    stack = []
    for ch in str:
        if ch=='(' or ch=='[' or ch == '{':
            stack.append(ch)
        else:
            if stack[-1] != bracktes[ch]:
                return False
            else:
                stack.pop()
    
    if stack: 
        return False
    return True

        

test_str1 = "([])[]({})"
test_str2 = "([)]"
test_str3 = "((()"
print(balanced_brackets(test_str1))
print(balanced_brackets(test_str2))
print(balanced_brackets(test_str3))

那有没有空间复杂度为O(1)的解法呢,有的!
我们可以借用双指针的方法。

#include <iostream>
using namespace std;
bool balanced_brackets(string str) {
       int i = -1;
       for(auto& ch:str){
        if(ch == '(' || ch== '[' || ch== '{'){
            str[++i] = ch;
        }else{
            if(i>=0 && ((str[i]=='(' && ch==')') || (str[i]=='{' && ch=='}') || (str[i]=='[' && ch==']'))){
                i--;
            }else{
                return false;
            }
        }
        
       }
       return i==-1;
}
 
int main()
{
    string test_str1 = "{()}[]";
    string test_str2 = "([)]";
 
    // Function call
    if (balanced_brackets(test_str1))
        cout << "Balanced";
    else
        cout << "Not Balanced";

    if (balanced_brackets(test_str2))
        cout << "Balanced";
    else
        cout << "Not Balanced"; 
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值