LeetCode387

力扣387题

题目描述:字符串中的第一个唯一字符

给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1

image.png

题解思路:

提供两种解题思路:

① 通过s.indexOf()s.lastIndexOf()查找字符串出现的位置,如果两个相等,则返回下标;出循环就说明没找到,返回-1;

② 借助arr[26]数组,包含26个英文字母,第一次遍历s获取s中元素出现的次数加在arr[26]中;第二次遍历s找出第一个出现次数为1的字符,返回下标。

//①
class Solution {
    public int firstUniqChar(String s) {
        for(int i=0;i<s.length();i++){
            int first = s.indexOf(s.charAt(i));
            int last = s.lastIndexOf(s.charAt(i));
            if(first == last){
                return i;
            }
        }
        //说明没找到
        return -1;
    }    
}
//②
class Solution {
    public int firstUniqChar(String s) {
        int arr[] = new int[26];//26个英文字母的数组
        for(int i=0;i<s.length(); i++){
            char ch = s.charAt(i);
            arr[ch - 'a']++;
        }

        //找arr[26]中下标为1的元素,然后返回
        for(int i=0;i<s.length(); i++){
            char ch = s.charAt(i);
            if(arr[ch - 'a'] == 1){
                return i;
            }
        }
        //没找到
        return -1;
    }    
}

猜你喜欢

转载自blog.csdn.net/Miss_croal/article/details/130394991