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