题目描述:

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.

解题思路:

开个26个数的数组,然后先对字符串过一遍,统计每个字母出现的次数,然后从头再国一遍,第一个字母数为1的即为首先出现并且只出现一次的字母。

代码如下:

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

  

相关文章:

  • 2022-02-11
  • 2021-11-02
  • 2021-08-23
  • 2021-05-15
  • 2021-12-17
  • 2022-01-03
  • 2022-12-23
猜你喜欢
  • 2022-02-07
  • 2022-01-21
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
相关资源
相似解决方案