请用Java语言写一个程序:给定一个字符串 s 找到 它的第一个不重复的字符并返回它的索引 。如果不存在则返回 -1
public class FirstUniqueChar {
public int firstUniqChar(String s) {
// 定义一个长度为 26 的数组,用于存储每个字母出现的次数
int[] count = new int[26];
// 统计每个字母出现的次数
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
}
// 找到第一个出现次数为 1 的字符
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
}
原文地址: https://www.cveoy.top/t/topic/bJmP 著作权归作者所有。请勿转载和采集!