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 }

类似Sort Characters By Frequency.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6252049.html