标签:nbsp empty where OWIN HERE parent push color example
Given a balanced parentheses string S
, compute the score of the string based on the following rule:
()
has score 1AB
has score A + B
, where A and B are balanced parentheses strings.(A)
has score 2 * A
, where A is a balanced parentheses string.Example 1: Input: "()" Output: 1 Example 2: Input: "(())" Output: 2 Example 3: Input: "()()" Output: 2 Example 4: Input: "(()(()))" Output: 6
计算由"("和")"组成的字符串的值。嵌套:乘2,并列:相加
用stack就可以。"("入栈,")",往前搜索第一个"(",如果中间有数字的,取出数字求和并乘以2;如果没有数字,直接压入"1"。
最后把stack中所有的数字相加。
1 class Solution { 2 public: 3 int scoreOfParentheses(string S) { 4 stack<string> s; 5 int i = 0; 6 while (i < S.length()) { 7 if (S[i] == ‘(‘) 8 s.push("("); 9 else { 10 if (s.top() == "(") { 11 s.pop(); 12 s.push("1"); 13 } 14 else { 15 int temp = 0; 16 while (s.top() != "(") { 17 temp += stoi(s.top()); 18 s.pop(); 19 } 20 s.pop(); 21 s.push(to_string(2 * temp)); 22 } 23 } 24 ++i; 25 } 26 int res = 0; 27 while (!s.empty()) { 28 res += stoi(s.top()); 29 s.pop(); 30 } 31 return res; 32 } 33 };
标签:nbsp empty where OWIN HERE parent push color example
原文地址:https://www.cnblogs.com/Zzz-y/p/9221472.html