1 转换成小写字母
public String toLowerCase(String str) {
String ans = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'A' && c <= 'Z') {
c = (char) (c + 32);
}
ans += c;
}
return ans;
}
public String toLowerCase2(String str) {
char[] a = str.toCharArray();
for (int i = 0; i < a.length; i++)
if ('A' <= a[i] && a[i] <= 'Z')
a[i] = (char) (a[i] - 'A' + 'a');//不需要知道a和A之间相差32
return new String(a);
}
2 最后一个单词的长度
3 宝石与石头
字符串中的第一个唯一字符
public int firstUniqChar(String s) {
int[] count = new int[26];// 存储各字符出现次数
int n = s.length();
for (int i = 0; i < n; i++) {
count[s.charAt(i) - 'a']++;
}
for (int i = 0; i < n; i++) {
if (count[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;// 无解
}
/**
* 如果题目要求不仅仅是小写字母,而是任意字符,可以使用HashMap
*/
public int firstUniqChar(String s) {
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < n; i++) {
if (count.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}