LeetCode笔记:387. 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.
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值