找尋字串中的第一個唯一字串
阿新 • • 發佈:2019-02-19
題目: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;
}