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;
}