387. First Unique Character in a String
Description
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.
class Solution {
public int firstUniqChar(String s) {
int[] freq = new int[26];
for (int i = 0; i < s.length(); i++) {
freq[s.charAt(i) - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (freq[s.charAt(i) - 'a'] == 1)
return i;
}
return -1;
}
}
本文介绍了一种高效算法,用于找出给定字符串中第一个不重复出现的字符及其索引位置。通过遍历字符串并使用数组记录每个字符出现次数的方法,实现了O(n)的时间复杂度。
484

被折叠的 条评论
为什么被折叠?



