字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0s = “loveleetcode”
返回 2提示:你可以假定该字符串只包含小写字母。
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
package _2020_07_08;
import java.util.HashMap;
import java.util.Map;
public class 字符串中的第一个唯一字符 {
public static void main(String[] args) {
String s = "loveleetcode";
System.out.println(firstUniqChar(s));
}
public static int firstUniqChar(String s) {
/* Map<String, Integer> map = new HashMap<String, Integer>();
*/
int[] ss = new int [26];
//第一次用给每一个元素,计数
for (char c : s.toCharArray()) {
ss[c - 'a']++;
}
//找出
for(int i = 0 ; i<s.length() ; i++){
if(ss[s.charAt(i)-'a'] == 1)
return i;
}
return -1;
}
}
方法二:Map
class Solution {
public int firstUniqChar(String s) {
Map<Character,Integer> map = new HashMap<Character , Integer>();
for(Character c : s.toCharArray()){
//如果不存在,计数1
if(!map.containsKey(c)){
map.put(c , 1);
}else{
map.put(c , map.get(c) + 1);
}
}
for(int i = 0 ; i < s.length() ; i++){
//.get() 取出 对应的键的值
if(map.get(s.charAt(i)) == 1){
return i;
}
}
return -1;
}
}