[LeetCode] 387. First Unique Character in a String

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

Note: You may assume the string contains 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 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11645580.html