[LeetCode] 387. First Unique Character in a String
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
Example 1:
Input: s = "leetcode" Output: 0
Example 2:
Input: s = "loveleetcode" Output: 2
Example 3:
Input: s = "aabb" Output: -1
Constraints:
1 <= s.length <= 105
s
consists of only lowercase English letters.
字符串中的第一个唯一字符。
题意是给一个字符串,请输出第一个出现的独一无二的字符,或者说请输出第一个出现的在整个字符串里面只出现过一次的字符。
还是counting sort的思路。对 input 数组扫描两次。第一次需要用 hashmap 记录所有字符出现的次数,第二次需要找到的是只出现过一次的字符。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int firstUniqChar(String s) { 3 int[] count = new int[26]; 4 for (int i = 0; i < s.length(); i++) { 5 count[s.charAt(i) - 'a']++; 6 } 7 for (int j = 0; j < s.length(); j++) { 8 if (count[s.charAt(j) - 'a'] == 1) { 9 return j; 10 } 11 } 12 return -1; 13 } 14 }
JavaScript实现
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var firstUniqChar = function(s) { 6 let map = {}; 7 for (let i = 0; i < s.length; i++) { 8 let cur = s.charAt(i); 9 if (!map[cur]) { 10 map[cur] = 1; 11 } else { 12 map[cur]++; 13 } 14 } 15 16 for (let j = 0; j < s.length; j++) { 17 let cur = s.charAt(j); 18 if (map[cur] === 1) { 19 return j; 20 } 21 } 22 return -1; 23 };