以下是我的代码。问题是找到给定字符串中的第一个唯一(不重复)字符,我是Java的初学者,所以现在我想知道如何调试代码......至于我有限的知识我甚至不知道如何开始调试......谢谢!
public class Solution {
public int firstUniqChar(String s) {
//My idea without referring to any other solution.
//put the all character into the hashmap, and delete the key if
//there is duplicate value, then get the first key of
//the remaining map, that is the smallest index of the unique
//character;
Map<Integer,Character> hmap=new HashMap<Integer,Character>();
int index = 0;
for (int i = 0; i < s.length(); i++){
//int value=(int)((Integer)map.get(a[i]));
char charI = s.charAt(i);
index ++;
hmap.put(index, charI);
//Error: cannot find this method;
while (hmap.ContainsValue(charI)){
hkey = charI.getkey();
hkey.remove();
}
}
//to return the index of the first key in the hashmap.
//Error: illegal start of type;
return hmap.get(hmap.keySet().toArray()[0]);
}
}
答案 0 :(得分:0)
在此代码中,您将字符串s转换为char数组。从char数组中取一个char并将其与数组中的所有其他字符进行比较。如果找不到(除了它自己),你打破循环并打印它。这样您就可以在字符串中找到第一个唯一字符:
public static void main(String[] args) {
String s = "abcd, afsfsfs, abcdef, 90> 20, abeds";
char[] charArray = s.toCharArray();
char current = 0;
for (int i = 0; i < charArray.length; i++) {
boolean contains = false;
current = charArray[i];
int j = 0;
while (j < charArray.length) {
if (charArray[i] == charArray[j] && i != j) {
contains = true;
break;
}
j++;
}
System.out.println("current=" + current + " " + contains);
if (j == charArray.length && !contains)
break;
}
System.out.println(current);
}
打印:
current=a true
current=b true
current=c true
current=d true
current=, true
current= true
current=a true
current=f true
current=s true
current=f true
current=s true
current=f true
current=s true
current=, true
current= true
current=a true
current=b true
current=c true
current=d true
current=e true
current=f true
current=, true
current= true
current=9 false
9