Contact me:

算法12 leetcode387 字符串中的第一个唯一字符

想法

终于写了一个比参考代码更优的解,没白花这么长时间思考!😁
看到题目应该马上可以想出最简单的解,就是统计一遍然后查找为1的值。但是我们肯定是要找更优解的
∴我想到用边查找边匹配的方法My code

题目

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

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

提示:你可以假定该字符串只包含小写字母

链接
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

代码code

My code

从头开始向后查找匹配,若该字母匹配则记录;之后查找先在记录中查询是否之前匹配过

class Solution {
    public int firstUniqChar(String s) {
        int p=-1,j=0;
        int [] count=new int[26];
        char[] sc=s.toCharArray();
//  from 0 to end
        for(int i=0;i< sc.length;i++){
//  the letter has matched--pass
            if(count[sc[i]-'a']==0) {
//  search after i
                for (j = i + 1; j < sc.length; j++) {
                    if (sc[i] == sc[j]) {
                        count[sc[i] - 'a']++;
                        break;
                    }
                }
//  no match then j out index
                if (j == sc.length) {
                    p = i;
                    break;
                }
            }
        }
    return p;
    }

}

参考代码other's code

从前往后,从后往前 相同则是唯一值

public int firstUniqChar(String s) {
     for (int i = 0; i < s.length(); i++)
         if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i)))
             return i;
     return -1;
 }

作者:数据结构和算法
[链接](https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/?discussion=6TyKA7)
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted @ 2021-11-04 10:13  impwa  阅读(23)  评论(0编辑  收藏  举报