[题目]
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.
[题目解析] 根据题意,思路比较简单,遍历字符串,用map存储对应字符以及出现次数,再次遍历原字符串,当出现第一个出现一次的字符时,返回对应的index即可,考虑到Note中提示的字符串只考虑小写字母组成的情况,可以用一个26位的数组表示map结构,代码如下。
public int firstUniqChar(String s) { if(null == s || 0 == s.length() ) return -1; int[] hash = new int[26]; char[] array = s.toCharArray(); for(int i = 0; i < array.length; i++){ int num = array[i] - ‘a‘; hash[num]++; } for(int i = 0; i < array.length; i++){ int num = array[i] - ‘a‘; if(hash[num] == 1){ return i; } } return -1; }
时间: 2024-10-11 06:07:11