如何在不使用诸如length()
,toCharArray()
,charAt()
之类的Java方法中使用String Class的内置方法的情况下找到字符串中的重复字符?
在面试中提问,请给我解决方案
input : abcdeddrb
output: db
答案 0 :(得分:2)
您可以通过反射来做到这一点:
public String findDuplicateChars(String input)
throws NoSuchFieldException, IllegalAccessException {
Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
char[] chars = (char[]) valueField.get(input);
List<Character> duplicatedChars = new ArrayList<>();
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
for (int j = i + 1; j < chars.length; j++) {
char anotherChar = chars[j];
if (aChar == anotherChar) {
if (!duplicatedChars.contains(aChar)) {
duplicatedChars.add(aChar);
}
}
}
}
char[] charArray = new char[duplicatedChars.size()];
for (int i = 0; i < duplicatedChars.size(); i++) {
charArray[i] = duplicatedChars.get(i);
}
return new String(charArray);
}
由于b
是第一个重复的char
,因此输出将是bd
,而不是db
。
也许面试问题的要点是检查您是否知道反思,或者检查您是否尝试通过回答“为什么要这样做?”来退出面试。
答案 1 :(得分:0)
我在这里的猜测是,您的面试官希望您使用地图来跟踪看到过哪些字符,哪些没看到过。
String input = "abcdeddrb";
Map<Character, Integer> map = new HashMap<>();
for (int i=0; i < input.length(); ++i) {
Integer count = map.get(input.charAt(i));
map.put(input.charAt(i), count == null ? 1 : count + 1);
}
map.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.forEach(System.out::println);
b=2
d=3
答案 2 :(得分:0)
也许将String
更改为CharSequence并将其方法用作charAt
CharSequence cs = s;
答案 3 :(得分:0)
public static void main(String[] args) {
String testStr = "abcdeddrb";
Map<Character, Integer> map = new HashMap<>();
Map<Character, Integer> duplicateStrMap = null;
int count = 0;
int i = 0;
CharacterIterator it = new StringCharacterIterator(testStr);
// Loop Characters in a String.
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
if(map.containsKey(c)){
if(duplicateStrMap == null){
duplicateStrMap = new HashMap<>();
}
duplicateStrMap.put(c, count);
count++;
}
else{
map.put(c, ++i);
}
}
// Print Results
if(duplicateStrMap != null){
System.out.println("Total Duplcates Found :"+duplicateStrMap.size());
Iterator<Character> itr = duplicateStrMap.keySet().iterator();
System.out.println("Duplicate Characters :");
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
输出:
发现重复总数:2
重复字符:
b
d