1209. Delete all neighboring string duplicates II [to be optimized]

topic:

Give you a string s, "k-fold delete duplicates" will select k neighboring and equally from the letters s and delete them, so that the left and right omitted string together . 

You need to be repeated infinitely s such a delete operation can not continue until so far. 
After you perform all of the deletion and returns the resulting string. 
The answer to this question guaranteed to be unique. 

Example 1 : 
Input: S = "ABCD", K = 2 
Output: "ABCD" 
Explanation: the content is not to be deleted. 

Example 2 : 
Input: S = "deeedbbcccbdaa", K =. 3 
Output: "AA" 
explanation: 
delete "eee" and "ccc", to give "ddbbbdaa" 
delete "bbb", to give "dddaa" 
Last Delete "ddd" to give "aa" 

example 3 : 
input: S = "pbbcggttciiippooaais",
 

2 <= k <= 10 ^

Source: stay button (LeetCode) 
link: HTTPS: // leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string-ii

Analysis: string to match the length of the continuous presence of the length of the input string, there is, delete it, and then continues to match, to give the final result. There is a recursive traversal of thought here. I do not think the string when regular, regular use appears to match, the match result of the split continues to match.

However, in such a way to write will time out in some test cases LeetCode particularly long, the follow-up to optimize it.

public String removeDuplicates(String s, int k) {
    //定义正则串
    Pattern pattern = Pattern.compile("([a-z])\\1{" + (k - 1) + "}");
    Matcher matcher = pattern.matcher(s);
    String res = "";
    if (matcher.find()) {
        matcher.reset();
        while (matcher.find()) {
            res = matcher.group(0);
            s = s.replace(res, "");
            s = removeDuplicates(s, k);
        }
        return s;
    } else {
        return s;
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/doona-jazen/p/11942270.html