从字符串中删除连续重复的字符。

huangapple go评论77阅读模式
英文:

Remove consecutive duplicate characters from a String

问题

/**
 * 递归地从字符串中移除重复字符。
 * 如果连续的两个或更多重复字符的大小写不同,则应保留第一个字符。
 * @param word 可能包含连续重复字符的单词。
 * @return 不包含任何连续重复字符的单词。
 */
public static String dedupeChars(String word) {
    if (word.length() <= 1)
        return word;

    if (word.substring(0, 1).equalsIgnoreCase(word.substring(1, 2)))
        return dedupeChars(word.substring(1));
    else
        return word.substring(0, 1) + dedupeChars(word.substring(1));
}
英文:

I'm trying to remove duplicate characters from a string recursively.
I don't know how to fix this code to remain the first character when characters have different cases.

/**
     * Remove consecutive duplicate characters from a String. &lt;br&gt;
     * Case should not matter, if two or more consecutive duplicate &lt;br&gt;
     * characters have different cases, then the first letter should be kept.
     * @param word A word with possible consecutive duplicate characters.
     * @return A word without any consecutive duplicate characters.
     */

    public static String dedupeChars(String word){

        if ( word.length() &lt;= 1 )
            return word;

       if( word.substring(0,1).equalsIgnoreCase(word.substring(1,2)) )    	 
    	    return dedupeChars(word.substring(1));

       else
            return word.substring(0,1) + dedupeChars(word.substring(1));

    }

答案1

得分: 4

你走在正确的轨道上,但你的逻辑有点问题。考虑一下这个版本,代码下面有解释:

public static String dedupeChars(String word) {
    if (word.length() <= 1) {
        return word;
    }

    if (word.substring(0, 1).equalsIgnoreCase(word.substring(1, 2))) {
        return dedupeChars(word.substring(0, 1) + word.substring(2));
    } else {
        return word.substring(0, 1) + dedupeChars(word.substring(1));
    }
}

System.out.println(dedupeChars("aaaaBbBBBbCDdefghiIIiJ"));

这会输出:

aBCDefghiJ

对于算法的解释,你的基本情况是正确的,对于单个字符的单词,我们只返回该字符。对于第一个字符与第二个字符相同的情况,我们切掉第二个字符,然后再次递归调用 dedupeChars()。例如,以下是对上面所示输入字符串的处理过程:

aaaaBbBBBbCDdefghiIIiJ
aaaBbBBBbCDdefghiIIiJ
aaBbBBBbCDdefghiIIiJ
aBbBBBbCDdefghiIIiJ

也就是说,我们切掉重复的字符,始终保留第一个出现的字符,直到没有更多重复为止。

顺便说一句,在实际中,你可能会想要使用正则表达式来实现一个更简洁的解决方案:

String input = "aaaaBbBBBbCDdefghiIIiJ";
input = input.replaceAll("(?i)(.)\+", "$1");
System.out.println(input);

这会输出:

aBCDefghiJ

在这里,我们只是告诉正则表达式引擎删除所有单个字母的重复,只保留系列中的第一个字母。

英文:

You were on the right track, but your logic was a bit off. Consider this version, with explanation below the code:

public static String dedupeChars(String word) {
    if (word.length() &lt;= 1) {
        return word;
    }

    if (word.substring(0,1).equalsIgnoreCase(word.substring(1,2))) {
        return dedupeChars(word.substring(0, 1) + word.substring(2));
    }
    else {
        return word.substring(0,1) + dedupeChars(word.substring(1));
    }
}

System.out.println(dedupeChars(&quot;aaaaBbBBBbCDdefghiIIiJ&quot;));

This prints:

aBCDefghiJ

For an explanation of the algorithm, your base case was correct, and for a single character word, we just return than character. For the case where the first character be identical to the second one, we splice out that second character and then recursively call dedupeChars() again. For example, here is what happens with the input string shown above:

aaaaBbBBBbCDdefghiIIiJ
aaaBbBBBbCDdefghiIIiJ
aaBbBBBbCDdefghiIIiJ
aBbBBBbCDdefghiIIiJ

That is, we splice out duplicates, always retaining the first occurrence, until there are no more duplicates.

By the way, in practice you might instead want to use regex here, for a much more concise solution:

String input = &quot;aaaaBbBBBbCDdefghiIIiJ&quot;;
input = input.replaceAll(&quot;(?i)(.)\+&quot;, &quot;$1&quot;);
System.out.println(input);

This prints:

aBCDefghiJ

Here we just tell the regex engine to remove all duplicates of any single letter, retaining only the first letter in the series.

答案2

得分: 0

我有另一种方法来实现您的目的,我认为您的代码太复杂了,用于去除重复字符(忽略大小写,只保留第一个字符)。

public static String removeDup(String s) {
    char[] chars = s.toCharArray();
    StringBuilder sb = new StringBuilder();
    for (int i = chars.length - 1; i > 0; i--) {
        if (chars[i] == chars[i - 1]) {
            continue;
        }
        if (chars[i] < 97) {
            if (chars[i] == (chars[i - 1] - 32)) {
                continue;
            }
        } else {
            if (chars[i] == (chars[i - 1] + 32)) {
                continue;
            }
        }
        sb.append(chars[i]);
    }
    sb.append(chars[0]);
    return sb.reverse().toString();
}

对于输入字符串 "aaaaBbBBBbCDdefghiIIiJ",输出将是 "aBCDefghiJ"。

英文:

I have a different way to achieve your purpose
and I think your code is too expensive to remove duplicate characters(ignore uppercase or lowercase,just keep the first one).

public static String removeDup(String s) {
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = chars.length - 1; i &gt; 0; i--) {
  if (chars[i] == chars[i - 1]) {
    continue;
  }
  if (chars[i] &lt; 97) {
    if (chars[i] == (chars[i - 1] - 32)) {
      continue;
    }
  } else {
    if (chars[i] == (chars[i - 1] + 32)) {
      continue;
    }
  }
  sb.append(chars[i]);
}
sb.append(chars[0]);
return sb.reverse().toString();}

For the input "aaaaBbBBBbCDdefghiIIiJ" the output will be "aBCDefghiJ"

huangapple
  • 本文由 发表于 2020年9月18日 13:35:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63949882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定