Leetcode387. First Unique Character in a String

来源:互联网 发布:github.io 绑定域名 编辑:程序博客网 时间:2024/05/10 01:20

一、题目

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.

二、思路

统计出s字符串中每个字符出现的字数,然后遍历次数,第一个为1的,则返回该字符的下标;否则则返回-1
三、代码

public class Solution {
    public int firstUniqChar(String s) {
        char[]s1=s.toCharArray();
if(s.length()==0)
return -1;
int []a=new int [26];//定义一个26个数的数组
//把s中每个字符出现的次数统计出来
for(int i=0;i<s.length();i++){
a[s1[i]-'a']++;
}
//如果字符出现的次数为1,则返回该字符的下标;否则则返回-1
for(int i=0;i<s.length();i++){
if(a[s1[i]-'a']==1)
return i;
}
return -1;

    }
}
1 0
原创粉丝点击