首页 > 试题广场 >

最长有效的括号字符子序列

[编程题]最长有效的括号字符子序列
  • 热度指数:754 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个字符串s,里面可能含有若干括号和小写英文字母,请你判断最长有效的括号字符子序列有哪些,放在一个数组里面返回(你不用在乎序列在数组里面的顺序)。
最长有效括号字符子序列的标准如下:
1.每一个左括号,必须有对应的右括号和它对应
2.字母的位置以及存在对括号字符子序列的合法性不受影响
3.子序列是不连续的,比如"()("的子序列有"()",")(","()(","(("
4.相同的括号字符子序列只保留一个,比如"())"有2个子序列"()",但是最后只保留一个"()"

数据范围:
0<=s.length<=25
s最多有20个括号,括号为'('与')',最多有5个小写英文字母
示例1

输入

"()())"

输出

["(())","()()"]

说明

2个都是最长的,长度都为4,["()()","(())"]也是一个正确的答案 
示例2

输入

")("

输出

[""]
示例3

输入

"(a))"

输出

["(a)"]

说明

只有一个有效且最长的 
class Solution {
public:
    int maxscore;
    int length;
    int n;
    unordered_set<string> hash;
    //左括号是1分 右括号 是-1分 合规的字符串一定时是0
    void dfs(string s, int score,string buf,int l,int r,int index){
        //如果出现删过头或者分数出现负数或者超过最大数返回
        if(l<0||r<0||score<0||score>maxscore)
            return;
        if(l==0&&r==0&&buf.length()==length)
            hash.insert(buf);
        if(index==n)
            return;

        char ch = s[index];
        if(ch=='('){
            dfs(s, score + 1, buf + '(', l, r, index + 1);//选择添加(括号 则+1分 继续遍历
            dfs(s, score, buf, l - 1, r, index + 1);//选择不添加左括号相当于删除左括号 则分数不变 继续遍历
        }
        else if(ch==')'){
            dfs(s, score - 1, buf + ')', l, r, index + 1);//选择添加)括号 则-1分 继续遍历
            dfs(s, score, buf, l, r - 1, index+1);//选择不添加右括号相当于删除右括号 则分数不变 继续遍历
        }else{
            dfs(s, score, buf + ch, l, r, index + 1);//遇到其他字符 直接添加 继续遍历
        }
    }

        vector<string> maxValidParenthesesStr(string s){
            //合规的字符串 分数一定是0
            //分数一定不会超过maxscore,maxscore就是所有可匹配的(都在左边,一直+1,能达到的最大分数
            maxscore = 0;
            n = s.size();
            int left = 0;
            int right = 0;
            int l = 0, r = 0;
            length = 0;
            for(auto&ch:s){
                if(ch=='('){
                    //统计左括号的数量
                    //需要删除的左括号的数量
                    l++;
                    left++;
                }
                else if(ch==')'){
                    //统计右括号数量
                    if(l!=0)
                        l--;//遇到可能匹配的右括号
                    else
                        r++;//需要删除的右括号的数量
                    right++;
                }
            }
            length = n - l - r;//字符串中除了左括号和右括号以外的应该有的长度
            maxscore = left < right ? left : right;//最大分数为可匹配的左括号或右括号的数量
            dfs(s, 0, "", l, r, 0);
            return {hash.begin(), hash.end()};
        }
};

发表于 2022-05-28 11:51:10 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串一维数组
     */
   private List<String> res3 = new ArrayList<String>();

	public String[] maxValidParenthesesStr(String s) {
		int lremove = 0;
		int rremove = 0;
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				lremove++;
			} else if (s.charAt(i) == ')') {
				if (lremove == 0) {
					rremove++;
				} else {
					lremove--;
				}
			}
		}
		helper(s, 0, lremove, rremove);
		String[] strings = new String[res3.size()];
		return res3.toArray(strings);
	}

	private void helper(String str, int start, int lremove, int rremove) {
		if (lremove == 0 && rremove == 0) {
			if (isValid2(str)) {
				res3.add(str);
			}
			return;
		}

		for (int i = start; i < str.length(); i++) {
			if (i != start && str.charAt(i) == str.charAt(i - 1)) {
				continue;
			}
			// 如果剩余的字符无法满足去掉的数量要求,直接返回
			if (lremove + rremove > str.length() - i) {
				return;
			}
			// 尝试去掉一个左括号
			if (lremove > 0 && str.charAt(i) == '(') {
				helper(str.substring(0, i) + str.substring(i + 1), i, lremove - 1, rremove);
			}
			// 尝试去掉一个右括号
			if (rremove > 0 && str.charAt(i) == ')') {
				helper(str.substring(0, i) + str.substring(i + 1), i, lremove, rremove - 1);
			}
		}
	}

	//判断是否为有效的括号对
	private boolean isValid2(String str) {
		int cnt = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == '(') {
				cnt++;
			} else if (str.charAt(i) == ')') {
				cnt--;
				if (cnt < 0) {
					return false;
				}
			}
		}
		return cnt == 0;
	}
}

发表于 2022-03-09 15:47:15 回复(0)

问题信息

上传者:牛客301499号
难度:
2条回答 2116浏览

热门推荐

通过挑战的用户

查看代码