删除字符串中的重复字符

山姆·洛特(Sam Lot)

这来自破解《编码面试书》。

设计一种算法并编写代码以删除字符串中的重复字符,而无需使用任何其他缓冲区。注意:一个或两个其他变量都可以。不是数组的额外副本。

在书中它说时间复杂度是$ O(N ^ 2)$。从解决方案中我们如何分辨时间复杂度为$ O(N ^ 2)$?我对解决方案如何删除重复字符有疑问。我已将它们包含在下面的嵌入式注释中。

   public static void removeDuplicates(char[] str) {
      if (str == null) return; // if the array is empty return  nothing?
      int len = str.length; // get the length of the array 
      if (len < 2) return; // if the array length is only 1 return nothing?
      int tail = 1; // initialise tail variable as 1 ! 
      // Why are we starting at second character here (at i = 1),why not start at i = 0 ? 
      for (int i = 1; i < len; ++i) { 
        int j;

        for (j = 0; j < tail; ++j) { // so are we checking if j is less then 1 as tail has been initialized to 1 
          if (str[i] == str[j]) break; // stop, if we find duplicate.
        }

        if (j == tail) { why are we comparing j to tail(1) here ?
          str[tail] = str[i]; // assigning the value 
          ++tail; // incrementing tail
        }
      }
      str[tail] = 0; //setting last element as 0 
    }


 - 
让·弗朗索瓦·萨瓦德

我完全依赖@pbabcdefp注释,因为我懒于对其进行测试,但是看来您的算法无法正常工作。

无论如何,我还是不喜欢它,在这里我会用注释中的解释来做到这一点:

public static void main(String[] args) {
    removeDuplicates(new char[]{'a','a','b','b','c','d','c'});
}

public static final void removeDuplicates(char[] str)
{
    /*
     * If the str is not instantiated, or there is maximum 1 char there is no need to remove duplicates as 
     * it is just impossible to have duplicate with 1 char.
    */
    if (str == null || str.length < 2)
        return;

    //loop over each char
    for(int i = 0; i < str.length; i++)
    {
        //no need to check with earlier character as they were already checked, so we start at i + 1
        for(int j = i + 1; j < str.length; j++)
        {
            //if they match we clear
             if(str[j] == str[i])
                str[j] = ' ';
        }
    }

    System.out.println(str);
}

那会输出a b cd

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

删除字符串中的重复字符

来自分类Dev

删除字符串中的重复字符

来自分类Dev

从字符串中删除重复字符

来自分类Dev

从字符串中删除重复的字符

来自分类Dev

删除字符串中重复的字符

来自分类Dev

从字符串中删除重复的子字符串

来自分类Dev

删除xslt中重复的字符串

来自分类Dev

从字符串中删除重复项

来自分类Dev

从字符串中删除重复的行

来自分类Dev

从列表中删除重复的字符串?

来自分类Dev

从字符串中删除重复项

来自分类Dev

删除字符串中的重复打孔

来自分类Dev

从字符串中删除重复项

来自分类Dev

在Java中删除重复的字符串

来自分类Dev

从列表中删除重复的字符串?

来自分类Dev

删除mysql中重复的字符串

来自分类Dev

从字符串中删除重复的单词

来自分类Dev

在 Python 中删除字符串而不删除重复字符

来自分类Dev

如何从Bash中的字符串中删除重复的字符?

来自分类Dev

从C中的字符串中删除重复的字符

来自分类Dev

从 Python 中的字符串中删除特定的重复字符

来自分类Dev

在python中删除字符串中的连续重复字符

来自分类Dev

删除重复的字符串

来自分类Dev

使用STL从字符串中删除重复的字符

来自分类Dev

从字符串中删除重复字符的算法

来自分类Dev

递归删除字符串中的重复字符

来自分类Dev

计算字符串中的字符数并删除重复项

来自分类Dev

删除字符串中重复的相邻字符

来自分类Dev

删除字符串中重复的字符集