计算有效的字符串长度

计算有效的字符串长度规则 给定一个只包含两种字符的字符串 其他字符均为无效 1 任何左括号 必须有相应的右括号 2 任何右括号 必须有相应的左括号 3 左括号 必须在对应的右括号之前 4 有效字符的长度为左括号和右括号的相加 include lt

大家好,我是讯享网,很高兴认识大家。

规则  :给定一个只包含两种字符的字符串:( ,) ,其他字符均为无效

1、任何左括号 ( 必须有相应的右括号 )。
2、任何右括号 ) 必须有相应的左括号 ( 。
3、左括号 ( 必须在对应的右括号之前 )。

4、有效字符的长度为左括号和右括号的相加。


讯享网

#include<iostream>
#include<string>
#include<vector>
#include<stack>

using namespace std;

int calc(const string& str,int& tail) {
    stack<char> s;
    int max = 0;
    int count = 0;
    while (tail >= 0) {
        if (str[tail] == '(' && s.size() == 0 || (str[tail]!=')' && str[tail]!='(')) {
            while (s.size() != 0) {
                s.pop();
            }
            printf("str is %c\n", str[tail]);
        
        }
        else if (str[tail] == '(' && s.top() == ')') {
            s.pop();
            ++count;
        }
        else if (str[tail] == ')') {
            s.push(str[tail]);
        }
        --tail;
    }
    if (max < count) {
        max = count;
    }
    printf("max is %d\n", max);
    return max*2;
}

int main(int argc, char* argv[]) {
    string str;
    cin >> str;
    int len = str.length();
    if (len < 2)
        cout << 0 << endl;
    --len;
    cout << calc(str,len) << endl;
    getchar();
    return 0;
}

小讯
上一篇 2025-03-13 17:31
下一篇 2025-03-23 10:49

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/51859.html