字符串中的第一个唯一字符
题目:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
解题思路:
相当于,如果一个字符在整个字符串只出现一次(即所谓的不重复),那么它的首次出现的索引和最后出现的索引的值应该是一样的。
运行代码:
public class Solution {
public static void main(String[] args) {
System.out.println(searchIndex("yayah"));
System.out.println(searchIndex("hyaya"));
}
public static int searchIndex(String s){
for(int i=0;i<s.length();i++){
//charAt(int index) 返回指定索引位置的char值
char ch = s.charAt(i);
//lastIndexOf() 返回在字符串中最右边出现的指定字符串的索引
//indexOf() 返回某个指定字符串的值在字符串中首次出现的位置
if(s.indexOf(ch)==s.lastIndexOf(ch)){
return i;
}
}
return -1;
}
}
结果:
4
0