java - 在Java中删除字符串中的重复字符

标签 java arrays string algorithm

我开始阅读著名的“破解编程面试”一书。

Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.

我在这里找到了一个类似的主题:Remove the duplicate characters in a string

作者给出的解决方案是:

  public static void removeDuplicates(char[] str) {
  if (str == null) return;
  int len = str.length;
  if (len < 2) return;

  int tail = 1;

  for (int i = 1; i < len; ++i) {
       int j;

       for (j = 0; j < tail; ++j) {
       if (str[i] == str[j]) break;
       }

       if (j == tail) {
       str[tail] = str[i];
       ++tail;
     }
  }
  str[tail] = 0;
 }

这里的问题是作者使用数组作为这个函数的参数。所以我的问题是:如何编写以 STRING 作为参数的算法?因为我觉得在这里使用数组真的更容易,就像你“避免了练习的困难”(在我看来,我是一个新的 Java 开发人员)。

如何编写这样的算法?

最佳答案

Java 字符串是不可变的,因此您不能在不将数组复制到缓冲区的情况下对字符串执行此操作。

关于java - 在Java中删除字符串中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830001/

相关文章:

java - Apache Commons Lang : Can the "incompatibilities" between 'lang' and 'lang3' cause different runtime results?

java - Octopus 在 jar 文件中部署替代变量

java - tomcat如何使用build.properties和build.xml?

c - 函数调用后输出不同的值?

python - Python 中的 String 是不可变的吗?

java - 使用soapui-pro-maven-plugin指定测试用例的标签

c# - 数组访问是否比模除法更快?

java - 仅对二维数组的行求和并将总和放入新数组中

java - 如何在 Java 中将字节数组转换为 Base64?

python - 在列名python中的特定位置保留字符串