leetcode - [387] First Unique Character in a String

2020/06/28

问题描述

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

计算字符串中第一个唯一字母的下标,若不存在,则返回-1

举个例子:

Examples:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

Note: You may assume the string contains only lowercase English letters.

字符串中仅包含小写字母。

解法1

梳理下思路:

首先,借助一个长度为26的整数数组,存储每个字母出现的次数。

然后,从头遍历原始字符串,若发现当前字母出现的次数为1时,即可返回其索引值。

若遍历结束还未找到这样的字母,则返回-1

来看下实现:

class Solution {
    public int firstUniqChar(String s) {
        
        int len = s.length();
        if (len == 0) return -1;
        
        int[] arr = new int[26];
        for (char c: s.toCharArray()){
            arr[c - 'a']++;
        }
        
        for (int i = 0; i < len; i++){
            if (arr[s.charAt(i) - 'a'] == 1){
                return i;
            }
        }
        
        return -1;
    }
}

Enjoy it !


一位喜欢提问、尝试的程序员

(转载本站文章请注明作者和出处 姚屹晨-yaoyichen

Post Directory