LeetCode387字符串中的第一个唯一字符

99 阅读1分钟

🍀字符串中的第一个唯一字符

描述:

 # 给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
 ​
  
 ​
 示例 1:
 ​
 输入: s = "leetcode"
 输出: 0
 示例 2:
 ​
 输入: s = "loveleetcode"
 输出: 2
 示例 3:
 ​
 输入: s = "aabb"
 输出: -1
  
 ​
 提示:
 ​
 1 <= s.length <= 105
 s 只包含小写字母

思考:

想到统计字符中不同字符的个数之类的提醒,第一反应应该就想到java的hashmap,hashmap的特性完美的满足了这类型题的要求。

实现:

 class Solution {
     public int firstUniqChar(String s) {
 ​
         char[] chars = s.toCharArray();
         Map<Character, Integer> map = new HashMap<>();
 ​
         for (char c : chars) {
             if (map.containsKey(c)){
                 Integer count = map.get(c);
                 map.put(c, ++count);
             }else {
                 map.put(c, 0);
             }
         }
 ​
         for (int i = 0; i < chars.length; i++) {
             if(map.get(chars[i]) == 1){
                 return i;
             }
         }
 ​
         return -1;
 ​
     }
 }

测试一下!

image.png

大佬的代码:

用数组要快得多。

 public int firstUniqChar(String s) {
        int[] arr = new int[26];
         int n = s.length();
         for (int i = 0; i < n; i++) {
             arr[s.charAt(i)-'a']++ ;
         }
         for (int i = 0; i < n; i++) {
             if (arr[s.charAt(i)-'a'] == 1) {
                 return i;
             }
         }
         return -1;
     }

\