我将于茫茫人海中访我唯一灵魂之伴侣;得之,我幸;不得,我命 。一徐志摩
要求:给定一个字符串,找到第一个不重复的字符,并返回它的索引。如果不存在,返回-1。
举例1:输入字符串 "leetcode",结果返回 0。
举例2:输入字符串 "loveleetcode",结果返回 2 。
思路:遍历整个字符串,定义一个变量用来记录该字符没有重复字符,当检验的字符与字符串中的其他字符进行比较时,如果不相等,变量自增。如果相等,变量归0,并跳出当前循坏。
时间复杂度O(n*n)
public class FirstUniqueCharacter {
public static void main(String[] args) {
String s1 = "z";
String s2 = "ababababaaa";
String s3 = "leetcode";
String s4 = "loveleetcode";
System.out.println("s1 FirstUniqueCharacter index is :"+firstUniqChar(s1));
System.out.println("s2 FirstUniqueCharacter index is :"+firstUniqChar(s2));
System.out.println("s3 FirstUniqueCharacter index is :"+firstUniqChar(s3));
System.out.println("s4 FirstUniqueCharacter index is :"+firstUniqChar(s4));
}
public static int firstUniqChar(String s) {
int index = -1;
if (s.length() == 1) {
return 0;
}else if(s.length() >1){
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
for (int j = 0; j < s.length(); j++) {
char temp = s.charAt(j);
if(j != i) {
if(ch != temp) {
index++;
}else {
index = -1;
break;
}
}else {
continue;
}
}
if (index >=0) {
index = i;
break;
}
}
return index;
}else {
return -1;
}
}
}
结果显示: