gpt4 book ai didi

java - 在 JAVA 中删除字符串中的重复项。不允许额外的数据结构

转载 作者:行者123 更新时间:2023-11-30 07:03:29 27 4
gpt4 key购买 nike

我最近遇到了这个问题,我实现了如下相同:

public class DuplicateRemover
{
public static void removeDuplicates(char[] str)
{
int len = str.length;

boolean[] hit = new boolean[256];

for(int i = 0; i < hit.length; i++)
hit[i] = false;

int noDupindex = 0;

for(int i = 0; i < len; i++)
{
if( !hit[str[i]] )
{
str[noDupindex++] = str[i];
hit[str[i]] = true;
}
}
str[noDupindex] = '\0';
}

public static void main(String[] args)
{
char[] x = "hhhhhhefffff".toCharArray();
removeDuplicates(x);
System.out.println(x);
}
}

但显示的输出是“hef hhefffff”。文字 '\0' 在末尾添加到 char 数组,并且在打印时仍然打印文字 '\0' 之后的元素。为什么会这样?如果我遗漏了什么,请告诉我。

最佳答案

x 不是字符串对象。它是一个字符数组。当您打印一个 char 数组时,每个元素都会被打印出来。它不会停在空字符上。

关于java - 在 JAVA 中删除字符串中的重复项。不允许额外的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com