2016年10月11日星期二

387. First Unique Character in a String

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

One Pass:

1. HashMap 存<character, firstIndex>, 加上一个set存当前count=1 的index,如果这个character又出现的话就从set删掉这个index

2.Two Pointer +count[]
count[array[fast]]++,当slow的count 不是1 的时候 用一个while loop slow++

  public int firstUniqChar(String s) {  
     int[] count = new int[26];  
     int len = s.length();  
     if(len == 0) return -1;  
     int slow = 0, fast = 0;  
      while (fast < len) {  
       count[(s.charAt(fast)-'a')]++;  
       while (slow < len && count[(s.charAt(slow)-'a')] > 1) slow++;   
       if (slow >= len) return -1;   
       fast++;  
     }  
     return slow;  
   }  

没有评论:

发表评论