Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.git
Examples:github
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.數組
這裏寫都是小寫字母,若是還有其餘奇怪的字符,那麼我就選擇使用Map來處理,和使用數組也是相似的code
ublic static int firstUniqChar(String s) { int[] arr = new int[26]; for(int i =0;i<s.length();i++){ arr[s.charAt(i) - 'a']++; } for(int j =0;j<s.length();j++){ if(arr[s.charAt(j) - 'a'] == 1){ return j; } } return -1; }
public static void main(String[] args) { System.out.println(firstUniqChar("leetcode")); System.out.println(firstUniqChar("loveleetcode")); }
輸出:blog
git:https://github.com/woshiyexinjie/leetcode-xinleetcode