题目:
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例 1:
输入:s = “abaccdeff”
输出:‘b’
示例 2:
输入:s = “”
输出:’ ’
限制:
0 <= s 的长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题过程1:
主要用到String.indexOf()
class Solution {
public char firstUniqChar(String s) {
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(s.indexOf(ch)==i && s.indexOf(ch,i+1)==-1)
return ch;
}
return ' ';
}
}
// indexOf(String str)
// 在给定符串中查找另一个字符串。
// indexOf(String str,int fromIndex)
// 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
执行结果1:
解题过程2:
申请一个新的字典数组,来自LeetCode用户:恩
class Solution {
public char firstUniqChar(String s) {
//创建‘a'-'z'的字典
int[] target = new int[26];
//第一次遍历,将字符统计到字典数组
for (int i = 0; i < s.length(); i++) {
target[s.charAt(i) - 'a']++;
}
//第二次遍历,从字典数组获取次数
for (int i = 0; i < s.length(); i++) {
if (target[s.charAt(i) - 'a'] == 1) return s.charAt(i);
}
return ' ';
}
}