码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]387. First Unique Character in a String第一个不重复字母

时间:2018-12-09 16:45:36      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:and   one pass   code   map   letters   思路   only   cond   exist   

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

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

 

Note: You may assume the string contain only lowercase letters.

 

思路

1.  use int array to simplify a hashmap

2. one pass to mark each char‘s occurrence

3. second pass to check 1st index whose char‘s occurrence == 1 

 

代码

 1 class Solution {
 2      public int firstUniqChar(String s) {
 3        int map [] = new int[256];
 4         for(int i = 0; i < s.length(); i ++)
 5             map [s.charAt(i) ] ++;
 6         for(int i = 0; i < s.length(); i ++)
 7             if(map [s.charAt(i) ] == 1)
 8                 return i;
 9         return -1;
10     }
11 }

 

[leetcode]387. First Unique Character in a String第一个不重复字母

标签:and   one pass   code   map   letters   思路   only   cond   exist   

原文地址:https://www.cnblogs.com/liuliu5151/p/10090777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!