前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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.
这个题目就是用一个数组保存每个字符出现过的自出,然后再遍历一次即可。 Your runtime beats 74.07% of java submissions.public class Solution {
public int firstUniqChar(String s) {
int[] alphabet = new int[26];
for(int i = 0 ; i < s.length(); i ++) alphabet[s.charAt(i) - 'a'] ++;
int result = -1;
for(int i = 0 ; i < s.length(); i ++) if(alphabet[s.charAt(i) - 'a'] ==1){result = i; break;}
return result;
}
}