我正在开发一种java方法,用于检查字符数组中的字符是否被字符包围。例如:abcdc,d 被 c 包围。例如:abccc,周围没有字母。这是我到目前为止所拥有的。
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(char letter : letters)
if(letters[letter-1] == letters[letter+1]){
result = true;
}
return result;
} }
所以我基本上有一个 for every 循环遍历字母中的字母,并检查该位置之前的字母是否等于该位置之后的字母。如果是,则意味着该字母被包围,并且应将结果更改为 true。 junit测试说if语句是错误的,但我不知道如何修复它。任何帮助表示赞赏。
最佳答案
您必须使用整数作为索引:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(int i = 1; i < letters.length - 1; i++) {
// You said that if the string is "abccc", should return false.
// So, we check if the previous or the next letter is different to
//the actual value of i
if((letters[i-1] == letters[i+1]) && (letters[i-1] != letters[i])) {
result = true;
}
}
return result;
}
关于java - Java 包围字符方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42890213/