【算法】1021. 删除最外层的括号(多语言实现)

123 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第15天,点击查看活动详情


1021. 删除最外层的括号:

有效括号字符串为空 """(" + A + ")"A + B ,其中 AB 都是有效的括号字符串,+ 代表字符串的连接。

  • 例如,"""()""(())()""(()(()))" 都是有效的括号字符串。

如果有效字符串 s 非空,且不存在将其拆分为 s = A + B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。

给出一个非空有效字符串 s,考虑将其进行原语化分解,使得:s = P1 + P2 + ... + Pk,其中 Pi 是有效括号字符串原语。

s 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 s

样例 1:

输入:
	s = "(()())(())"
	
输出:
	"()()()"
	
解释:
	输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
	删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。

样例 2:

输入:
	s = "(()())(())(()(()))"
	
输出:
	"()()()()(())"
	
解释:
	输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
	删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。

样例 3:

输入:
	s = "()()"
	
输出:
	""
	
解释:
	输入字符串为 "()()",原语化分解得到 "()" + "()",
	删除每个部分中的最外层括号后得到 "" + "" = ""

提示:

  • 1 <= s.length <= 10510^5
  • s[i]'('')'
  • s 是一个有效括号字符串

分析

  • 面对这道算法题目,二当家的陷入了沉思。

  • 根据题意,先要理解什么是原语

  • 原语本身是有效括号字符串。

  • 只要我们能找到原语,那么只需要把头尾字符去掉即可。


题解

rust

impl Solution {
    pub fn remove_outer_parentheses(s: String) -> String {
        let mut left = 0;
        s.chars().filter(|c| match c {
        '(' => {
            left += 1;
            left > 1
        },
        ')' => {
            left -= 1;
            left > 0
        },
        _ => false
        }).collect::<String>()
    }
}

go

func removeOuterParentheses(s string) string {
    var ans []rune
    left := 0
    for _, c := range s {
        if c == ')' {
            left--
        }
        if left > 0 {
            ans = append(ans, c)
        }
        if c == '(' {
            left++
        }
    }
    return string(ans)
}

typescript

function removeOuterParentheses(s: string): string {
    let ans = "";
    let left = 0;
    for (const c of s) {
        if ((c == '(' && ++left > 1) || (c == ')' && --left > 0)) {
            ans += c;
        }
    }
    return ans;
};

c

char * removeOuterParentheses(char * s){
    int size = 0;
    int left = 0;
    for (int i = 0; s[i]; ++i) {
        char c = s[i];
        if ((c == '(' && ++left > 1) || (c == ')' && --left > 0)) {
            s[size++] = s[i];
        }
    }
    s[size++] = '\0';
    return s;
}

c++

class Solution {
public:
    string removeOuterParentheses(string s) {
        string ans;
        int left = 0;
        for (char &c: s) {
            if ((c == '(' && ++left > 1) || (c == ')' && --left > 0)) {
                ans.push_back(c);
            }
        }
        return ans;
    }
};

java

class Solution {
    public String removeOuterParentheses(String s) {
        StringBuilder ans  = new StringBuilder();
        int           left = 0;
        for (char c : s.toCharArray()) {
            if ((c == '(' && ++left > 1) || (c == ')' && --left > 0)) {
                ans.append(c);
            }
        }
        return ans.toString();
    }
}

python

class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        ans, left = "", 0
        for c in s:
            if c == ')':
                left -= 1
            if left:
                ans += c
            if c == '(':
                left += 1
        return ans
        

原题传送门:https://leetcode.cn/problems/remove-outermost-parentheses/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~