我需要一个版本的java.lang.String.indexOf(String str,int fromIndex),它会忽略重复的字符,因为它会返回第一个单个字母的索引。
这与indexOf方法的String类不同,因为它要求字符串只是字符串的单个实例,因此如果字符串连续出现两次或更多次,则不会返回任何这些值。如果没有单个实例,则该方法应该像普通的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.
}
答案 0 :(得分:0)
有时,首先对问题进行建模会有所帮助。我们可以使用有限状态机对此进行建模。
使用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;
}
答案 1 :(得分:0)
以下代码很脏,但已通过您的要求。重构和进一步测试留给你。
private static int indexOfNoDup(String str, char c, int start) {
char[] array = str.toCharArray();
int length = array.length;
if (start < 0 || start >= length) {
throw new IndexOutOfBoundsException();
}
if (start == length - 1 && array[start] == c) {
return start;
}
for (int i = start; i < length; i++) {
while (i < length - 1 && array[i] == c && array[i + 1] == c)
i = i + 2;
}
if (array[i] == c) {
return i;
}
}
return -1;
}
答案 2 :(得分:-1)
您的代码将是:
int indexOfNoDup(string aChar, int startPosition){
int posInString; // character position in static String "string"
int lenString; // length of static String "string"
int pos; // temporal
for (posInString=startPosition, posInString<lenString; posInString)
{
if (aChar == string[posInStrings])
{
if ((posInString+1<lenString) && (aChar == String[posInStrings+1])) { // followed by same character
if(posInString+2<lenString){
return -1; // no more characters after successive charecters.
} else {
for (pos = posInString+2; (pos < lenString) && (aChar == string[pos]); pos++)
; // skip successive characers.
posInString = pos; // character at posInString is other character or end of string.
}
} else { // found isolated character!
return posInStrings;
}
}
}
}