题目:First Unique Character in a String
描述:
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 1;
Note: You may assume the string contain only lowercase letters.
####翻译:
得到一个字符串,找出第一个唯一的字符,并且返回它的序号,如果不存在唯一的字符,就返回-1;
####思路:
双层for循环,内层循环负责验证外层循环的字符是否是唯一的
####代码:
public static int firstUniqChar(String s) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
boolean uniq = true;
for (int j = 0; j < chars.length; j++) {
if (i == j)
continue;
if ((chars[j] - chars[i]) == 0) {
uniq = false;
break;
}else
uniq = true;
}
if (uniq)
return i;
}
return -1;
}