
力扣387题---字符串中的第一个唯一字符
给定一个字符串s,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1 。
示例 1:输入: s = "leetcode" 输出: 0
示例 2: 输入: s = "loveleetcode" 输出: 2
示例 3: 输入: s = "aabb" 输出: -1
提示:
1 <= s.length <= 10^5
s只包含小写字母
方法1:使用Java的api
public int firstUniqChar(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
return i;
}
}
return -1;
}
测试:
public class Main {
public static void main(String[] args) {
String str = "leetcode";
Main solution = new Main();
System.out.println(solution.firstUniqChar(str));
}
public int firstUniqChar(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
return i;
}
}
return -1;
}
}
输出:0
方法2:两次遍历法
第一遍先统计每个字符出现的次数,第二遍再次从前往后遍历字符串s中的每个字符,如果某个字符出现一次直接返回
public int firstUniqChar(String s) {
int[] array = new int[26];
char[] chars = s.toCharArray();
for (int i = 0; i < s.length(); i++)
array[chars[i] - 'a']++;
for (int i = 0; i < s.length(); i++) {
if (array[chars[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
测试:
public class Main {
public static void main(String[] args) {
String str = "loveleetcode";
Main solution = new Main();
System.out.println(solution.firstUniqChar(str));
}
public int firstUniqChar(String s) {
int[] array = new int[26];
char[] chars = s.toCharArray();
//先统计每个字符出现的次数
for (int i = 0; i < s.length(); i++)
array[chars[i] - 'a']++;
//然后在遍历字符串s中的字符,如果出现次数是1就直接返回
for (int i = 0; i < s.length(); i++) {
if (array[chars[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
}
输出:2