[LeetCode]387.First Unique Character in a String

题目描述:

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。
假设字符串只包含小写字母。
思路:
将s的所有字符存入一个hashmap,map<K,V> K 指字符,V指出现的次数。存入时每个字符依次判断是否在map中存在。
如果K存在,则map的V值+1
最后从0开始遍历map,判断第一次出现V的值等于1的即返回i

 1 public class Solution387 {
 2     public int firstUniqChar(String s) {
 3         if(s.length()==0||s==null){return -1;}
 4         HashMap<Character, Integer> map = new HashMap<>();
 5         char[] ch = s.toCharArray();
 6         for(int i = 0; i < s.length();i++){
 7             if(map.containsKey(ch[i])) map.put(ch[i], map.get(ch[i])+1);
 8             else {
 9                 map.put(ch[i], 1);
10             }
11         }
12         for(int i = 0; i < s.length();i++){
13             if(map.get(ch[i])==1){
14                 return i;
15             }
16         }
17         return -1;
18     }
19     public static void main(String[] args) {
20         // TODO Auto-generated method stub
21         Solution387 solution387 = new Solution387();
22         String s = "loveleetcode";
23         System.out.println(solution387.firstUniqChar(s));
24     }
25 
26 }

 

posted @ 2018-01-09 16:19  zlz099  阅读(117)  评论(0编辑  收藏  举报