gpt4 book ai didi

java - 不使用 HashMap 查找第一个非重复字符

转载 作者:行者123 更新时间:2023-12-02 04:48:40 26 4
gpt4 key购买 nike

我想找到字符串中的第一个非重复字符。我编写了以下函数,其中我陷入了一个点。 Google 告诉我这个的 hashmap 方法,但如果有人可以帮助我编写代码,我将不胜感激。

public static Character firstNonRepeatedChar(String line) {

Character c = null;
int strLength = line.length();

for (int i =0; i<strLength-1; i++){

int flag = 0;
for(int j = i+1; j<strLength-i; j++){

if(line.charAt(i) == line.charAt(j)){
flag++;
break;
}
else
continue;
}

if (flag==0){
c = line.charAt(i);
break;
}


}
return c;
}
}

问题:如何检查已经检查过一次的重复字符不会再次检查。例如:如果我的字符串是“hhello”,那么代码首先将索引 0 处的 h 与所有其他字符进行比较。因为它重复外部 for 循环的下一次迭代,其中 i 现在指向字符串的索引 1,即重复的 h 并将其与其余元素进行比较。由于它没有获得重复实例,因此它返回“h”作为非重复字符,这是错误的。

我该如何解决这个问题?有什么办法吗?请帮忙

编辑:重复字符不必是紧邻的下一个字符。例如:在字符串“helloWorld”中,字符“l”和“o”重复。 在字符串“hehelo”中,字符“h”和“e”是重复的,第一个非重复字符将是“l”

最佳答案

***对于所有重复情况

Character c = null;
int strLength = line.length();

for (int i = 0; i < strLength; i++) {

int flag = 0;
for (int j = 0; j < strLength; j++) {
if (line.charAt(i) == line.charAt(j) && i != j) {
flag = 1;
break;
}
}

if (flag == 0) {
c = line.charAt(i);
break;
}

}
return c;

检查起来很简单,你的逻辑很复杂。尝试这个立即重复的字符。

Character c = null;
int strLength = line.length();

for (int i = 0; i < strLength - 1;) {

int flag = 0;
int present_char_position = 0;

if (line.charAt(i) == line.charAt(i + 1)) {
flag++;
present_char_position = i;
i += 2;//jumping from those two character if matched
continue;
} else {
present_char_position = i;
i++;//if not matched go to next character
}

if (flag == 0) {
c = line.charAt(present_char_position);
break;
}

}
return c;

关于java - 不使用 HashMap 查找第一个非重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29455756/

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