387. 字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.
 

注意事项:您可以假定该字符串只包含小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

找出现次数用哈希思想解决问题,设map数组第一次遍历存储26个字母的出现次数,第二次遍历找到字符串第一个出现次数为1的字母,即字符串中第一个唯一字符。

 1 class Solution {
 2     public int firstUniqChar(String s) {
 3         char[] map = new char[26];
 4         char[] ch = s.toCharArray();
 5         for (char c : ch)
 6         {
 7             map[c-'a']++;
 8         }
 9         for (int i = 0; i < ch.length; i++)
10         {
11             if (map[ch[i]-'a'] == 1)
12             {
13                 return i;
14             }
15         }
16         return -1;
17     }
18 }
posted @ 2020-01-13 13:38  zjcfrancis  阅读(134)  评论(0编辑  收藏  举报