LeetCode笔记:387. First Unique Character in a String

来源:互联网 发布:我的世界手机版0.15js 编辑:程序博客网 时间:2024/06/06 18:41

问题:

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.
Note: You may assume the string contain only lowercase letters.

 大意:

给出一个字符串,找到其中第一个不重复的字母并返回它的序号。如果不存在,则返回-1。
例子:
s = “leetcode”
return 0.
s = “loveleetcode”
return 2.
注意:你可以假设字符串只包含小写字母。

思路:

最近连续几题都是关于字符串中字母的题目,也都强调了可以假设全为小写字母,基本养成了看到这种东西就想到要用26位数字数组记录的条件反射,这确实是一个很好的方法,实现出来也很快。这里的目的是找出第一个不重复的字母,那么首先肯定要遍历查看每个字母是否重复,所以要拿26位数字数组来记录每个字母出现的次数。因为要找出第一个不重复的,所以还要一个26位数字数组来记录每个数组第一次出现的位置。最后查看有哪些字母只出现了一次并且找到其中出现位置最早的那个字母就是了。

代码(Java):

public class Solution {    public int firstUniqChar(String s) {        char[] sArr = new char[s.length()];        sArr = s.toCharArray();        int[] sLetter = new int[26];// 记录出现次数        int[] sIndex = new int[26];// 记录首次出现位置        // 遍历记录次数和位置        int index = 0;        for (int i = 0; i < sArr.length; i++) {            if (sLetter[sArr[i] - 'a'] == 0) {                sIndex[sArr[i] - 'a'] = index;            }            index++;            sLetter[sArr[i] - 'a']++;        }        // 编辑次数数组,找到只出现一次的字母中出现位置最早的        int result = s.length();        for (int i = 0; i < 26; i++) {            if (sLetter[i] == 1 && sIndex[i] < result) result = sIndex[i];        }        if (result == s.length()) return -1;        else return result;    }}

版权所有:http://blog.csdn.net/cloudox_

0 0