LeetCode 387. First Unique Character in a String

原题链接在这里:https://leetcode.com/problems/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.

题解:

扫两遍string. 第一遍s.chatAt(i)的对应count++. 第二遍找第一个count为1的char, return其index.

Time Complexity: O(s.length()). Space: O(1), 用了count array.

AC Java:

 1 class Solution {
 2     public int firstUniqChar(String s) {
 3         if(s == null || s.length() == 0){
 4             return -1;
 5         }
 6         
 7         int [] count = new int[256];
 8         for(int i = 0; i<s.length(); i++){
 9             count[s.charAt(i)]++;
10         }
11         
12         for(int i = 0; i<s.length(); i++){
13             if(count[s.charAt(i)] == 1){
14                 return i;
15             }
16         }
17         
18         return -1;
19     }
20 }

AC C++:

 1 class Solution {
 2 public:
 3     int firstUniqChar(string s) {
 4         int map[256] = {0};
 5         for(char c : s){
 6             map[c]++;
 7         }
 8 
 9         for(int i = 0; i < s.size(); i++){
10             if(map[s[i]] == 1){
11                 return i;
12             }
13         }
14 
15         return -1;
16     }
17 };

类似Sort Characters By Frequency.

posted @ 2017-01-05 13:52  Dylan_Java_NYC  阅读(262)  评论(0编辑  收藏  举报