原题链接在这里: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.

相关文章:

  • 2022-02-11
  • 2021-11-02
  • 2021-08-23
  • 2021-05-15
  • 2022-01-03
  • 2022-12-23
  • 2021-12-17
猜你喜欢
  • 2022-01-21
  • 2022-02-07
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2022-12-23
相关资源
相似解决方案