字符串中的第一个唯一字符

40 阅读1分钟
// 字符串中的第一个唯一字符  
// 输入: s = "leetcode"  
// 输出: 0  
public static int firstUniqChar(String s){  
    HashMap<Character, Integer> pos = new HashMap<>();  
    LinkedList<Pair> queue = new LinkedList<Pair>();  
    int n = s.length();  
    for (int i = 0; i <n ; i++) {  
        char c = s.charAt(i);  
        if(!pos.containsKey(c)){  
            pos.put(c,i);  
            queue.offer(new Pair(c,i));  
        }else{  
            pos.put(c,-1);  
            while (!queue.isEmpty()&&pos.get(queue.peek().ch)==-1){ 
                queue.poll();  
            }  
        }  
    }  
    return queue.isEmpty()?-1:queue.poll().pos;  
}
class Pair{  
    char ch;  
    int pos;  
    Pair(char ch,int pos){  
        this.ch=ch;  
        this.pos=pos;  
    }  
}