387. First Unique Character in a String

来源:互联网 发布:今年淘宝双11 1元 编辑:程序博客网 时间:2024/06/03 16:33

题目描述:
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.

思路:

  因为小写字母的个数是有限的,一共26个,所以可以创建一个长度为26的整型数组。遍历给出的字符串,某个字母出现一次,整型数组对应位置的值加1。然后再遍历一次,按先后顺序检查每个字母对应位置的数值,第一个出现为1的即为所求。

代码

class Solution {    public int firstUniqChar(String s) {        int[] num = new int[26];        for(int i = 0;i<s.length();i++){            num[s.charAt(i)-'a']++;        }        for(int i =0;i<s.length();i++){            if(num[s.charAt(i)-'a']==1){                return i;                           }        }        return -1;    }}
原创粉丝点击