我正在寻找一种解决方案,以找到字符串中最后一个重复的字符,该字符表示“你今天过得怎么样”,它应该给出 y
作为答案。我曾尝试使用 Linked Hash Map 来获取有序的插入,但我得到的 d 是最后一个重复的。
String testString = "how are you doing today";
char[] testStringArray = testString.toCharArray();
Map<Character,Integer> map = new LinkedHashMap<>();
for( char i : testStringArray) {
if (!(i==' ')) {
if(map.containsKey(i) ) {
map.put(i, map.get(i)+1);
} else {
map.put(i, 1);
}
}
}
System.out.println(map);
List<Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
ListIterator<Entry<Character, Integer>> it = list.listIterator(list.size());
while(it.hasPrevious()) {
if(it.previous().getValue() > 1)
System.out.println(it.previous().getKey());
}
}
感谢您的帮助。
最佳答案
此代码从最后一个字符开始扫描,并检查它是否存在于第一个字符之前的剩余子字符串中:
String str = "how are you doing today";
int len = str.length();
int i = len - 1;
for (; i >= 1; i--) {
if (str.substring(0, i).contains(str.charAt(i) + "")) {
break;
}
}
if (i == 0) {
System.out.println("no repeating character");
} else
System.out.println(str.charAt(i));
关于java - 字符串中的最后一个重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38457233/