gpt4 book ai didi

Java String indexOf 忽略重复字符

转载 作者:行者123 更新时间:2023-12-01 06:15:14 25 4
gpt4 key购买 nike

我需要 java.lang.String.indexOf(String str, int fromIndex) 的一个版本,它可以忽略重复字符,因为它返回字母第一次出现的索引。

这与 String 类的 indexOf 方法不同,因为它要求字符串只是字符串的单个实例,因此如果字符串连续出现两次或多次,它将不会返回任何这些值。如果没有单个实例,该方法应该像普通的indexOf一样返回-1。

例如,我们将调用方法indexOfNoDup:

static String string = "aabaccbdd";

public static void main(String[] args)
{
indexOfNoDup("a", 0);
//Output: 3
//The first single occurrence of "a" is in position 3. The "a"s in position 0 and 1 are not returned because they are not single instances.

indexOfNoDup("b", 4);
//Output: 6
//The first single occurrence of "b" at or after position 4 is in position 6.

indexOfNoDup("c", 0);
//Output: -1
//There is no single instance of "c" in the line.

indexOfNoDup("a", 1);
//Output: 1
//The first single occurrence of "a" at or after position 1 is in position 1.
}

最佳答案

有时,首先对您的问题进行建模会有所帮助。我们可以使用有限状态机对此进行建模。

enter image description here

使用 draw.io 创建的图像

所以我们想要做的是实现该状态机。有几种方法可以做到这一点。这是一种这样的方法(假设我正确实现了它,但这应该不会太难调试):

int index = -1;
int state = 0;
while (index < string.length()) {
int new_index = string.indexOf(value, index + 1);
if (new_index == -1) {
switch (state) {
case 0: return -1;
case 1: return index;
case 2: return -1;
}
}
if (new_index == index + value.length()) {
if (state < 2) state++;
} else {
state = 0;
}
index = new_index;
}

对于单个字符的具体情况,我们可以这样做:

int index = -1;
int found_index = -1;
int state = 0;
while (index < string.length()) {
if (string.charAt(index + 1) == value) { //assuming value is type char, else do value.charAt(0)
if (state < 2) state++;
if (state == 1) found_index = index;
} else {
state = 0;
}
index++;
}
switch (state) {
case 0: return -1;
case 1: return found_index;
case 2: return -1;
}

关于Java String indexOf 忽略重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26599444/

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