有两种解决方法。

第一种,从前往后遍历,如果后面的字符与当前的字符相同,就直接跳过,如果不相同,就停止。代码如下:

private String doFilter(String text) {
        String newText = "";
        int i = 0;
        int j = i+1;
        newText += text.charAt(i);
        while(j < text.length()){
            if(text.charAt(i) == text.charAt(j)){
                j++;
            }else {
                i = j;
                j=i+1;
                newText += text.charAt(i);
            }
        }
        return newText;
    }

第二种,是只比较当前字符与前一个字符是否相等,如果相等就删除前一个字符,不相等则直接向下遍历。代码如下:

    private String doFilter2(String text) {
        StringBuffer newText = new StringBuffer(text);
        for(int i=1;i<newText.length();i++){
                if(newText.charAt(i) == newText.charAt(i-1)){
                    newText.deleteCharAt(i-1);
                    i--;
                }
        }
        return newText.toString();
    }

两种方法的时间复杂度与空间复杂度相同。

 

相关文章:

  • 2022-12-23
  • 2021-06-14
  • 2022-12-23
  • 2021-09-01
  • 2021-11-08
  • 2021-08-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2022-12-23
  • 2021-11-07
相关资源
相似解决方案