記得面試鵝廠的時候面試官問了一個類似算法的問題:
給出一個字符串,求出該字符串中只出現一次且排在最前面的字符
例如一個字符串:abcabcuio
我們可以看出u是隻出現一次且排在最前面的字符。
其實我能想到最快的速度也需要遍歷一遍後得到結果,我方法如下:如還有更好的方案請留言參考。
public static char getSingleLetter(String str){
char tagLab = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
int count = 1;
char keyStr = str.charAt(i);
System.out.println(keyStr);
if (null != map.get(keyStr)) {
count = map.get(keyStr) + 1;
map.replace(keyStr, count);
if (tagLab == keyStr ) {
tagLab = 0;
}
}else {
map.put(keyStr, count);
if (tagLab == 0) {
tagLab = keyStr;
System.out.println("最後執行的就是該字符的位置:"+i);
}
}
}
System.out.println(tagLab);
return tagLab;
}
打完這個方案之後面試官又進一步問我那怎麼最快拿到該字母在字符串的位置呢?
方案如下:
public static int getSinglePosition(String str){
char tagLab = 0;
int position = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
int count = 1;
char keyStr = str.charAt(i);
System.out.println(keyStr);
if (null != map.get(keyStr)) {
count = map.get(keyStr) + 1;
map.replace(keyStr, count);
if (tagLab == keyStr ) {
tagLab = 0;
}
}else {
map.put(keyStr, count);
if (tagLab == 0) {
tagLab = keyStr;
position = i;
System.out.println("最後執行的就是該字符的位置:"+i);
}
}
}
System.out.println(tagLab);
return position;
}