Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.數組
Examples:less
s = "leetcode" return 0. s = "loveleetcode", return 2.
難度: easycode
題目:給定字符串,找出第一個不重複的字符,並返回其下標。若是不存在則返回-1.leetcode
思路:數組分別記錄下標與出現次數。字符串
Runtime: 10 ms, faster than 93.94% of Java online submissions for First Unique Character in a String.
Memory Usage: 40 MB, less than 14.74% of Java online submissions for First Unique Character in a String.string
class Solution { public int firstUniqChar(String s) { int[] count = new int[26]; int[] index = new int[26]; int result = s.length(); for (int i = 0; i < result; i++) { char c = s.charAt(i); count[c - 'a']++; index[c - 'a'] = i + 1; } for (int i = 0; i < 26; i++) { if (1 == count[i]) { result = Math.min(result, index[i] - 1); } } return result >= s.length() ? -1 : result; } }