给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
代码一:数组存储统计字母出现频数
class Solution {
public int firstUniqChar(String s) {
int[] arr = new int[26];
int n = s.length();
for(int i = 0;i<n;i++){
arr[s.charAt(i)-'a']++;
}
for(int i = 0;i<n;i++){
if(arr[s.charAt(i)-'a']==1)
return i;
}
return -1;
}
}
int a = ''
代码二:哈希表统计
class Solution {
public int firstUniqChar(String s) {
Map<Character,Integer> frequency = new HashMap<Character,Integer>();
for(int i = 0;i<s.length();i++){
char ch = s.charAt(i);
frequency.put(ch,frequency.getOrDefault(ch,0)+1);
}
for(int i = 0;i<s.length();i++){
if(frequency.get(s.charAt(i))==1){
return i;
}
}
return -1;
}
}
getOrDefault(关键字,默认值)方法,当Map中有这个key时就返回对应的value,当不含有这个key时就返回默认值。
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}
put(k,v)
向Map中添加键值对
3.get(k)
返回对应的value
4.char类型到int型自动转化,比如
int j = 'a';
int i = 'c' - 80;
int k = 'c' - 'a';
System.out.println(j);
System.out.println(i);
System.out.println(k);
输出
97
19
2
但是,int类型转换为char类型要强制转换:
char ch1 = 'a';
char ch2 = 98;//允许
char ch3 = (char) (ch1+ch2-90);//需要加char强制转换,否则报错
int ch4 = (ch1+ch2-90);//char型和int型一起运算,就会自动转换为int型
System.out.println(ch1);
System.out.println(ch2);
System.out.println(ch3);
System.out.println(ch4);
结果
a
b
i
105