字符串类
leetcode 49. 字母异位词分组
方法一:将字符串按字符排序好作为key
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = String.valueOf(chars);
if (map.containsKey(key)) {
map.get(key).add(str);
} else {
List<String> list = new ArrayList<>();
list.add(str);
map.put(key, list);
}
}
return new ArrayList<List<String>>(map.values());
}
方法二:统计字符串每个字符出现的次数作为可以
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
int[] table = new int[26];
for (int i = 0; i < str.length(); i++) {
table[str.charAt(i) - 'a']++;
}
StringBuffer keySb = new StringBuffer();
for (int i = 0; i < 26; i++) {
keySb.append(table[i] + "#");
}
String key = keySb.toString();
if (map.containsKey(key)) {
map.get(key).add(str);
} else {
List<String> list = new ArrayList<>();
list.add(str);
map.put(key, list);
}
}
return new ArrayList<>(map.values());
}
leetcode 58. 最后一个单词的长度
public int lengthOfLastWord(String s) {
int count = 0;
int index = s.length() - 1;
//过滤空格
while (index >= 0 && s.charAt(index) == ' ') {
index--;
}
//计算最后一个单词的长度
for (int i = index; i >= 0; i--) {
if (s.charAt(i) == ' ') {
break;
}
count++;
}
return count;
}
leetcode 67. 二进制求和
提前申请好空间,避免后面需要重新申请
public String addBinary(String a, String b) {
if (a == null || a.length() == 0) {
return b;
}
if (b == null || b.length() == 0) {
return a;
}
if (a.length() < b.length()) {
return addBinary(b, a);
}
int len = a.length() + 1;
char[] newCharArray = new char[len];
int flag = 0;
int num = 0;
int gap = a.length() - b.length();
for (int i = a.length() - 1; i >= gap; i--) {
num = flag + a.charAt(i) + b.charAt(i - gap) - '0' * 2;
newCharArray[--len] = num % 2 == 0 ? '0' : '1';
flag = num / 2;
}
for (int i = gap - 1; i >= 0; i--) {
num = flag + a.charAt(i) - '0';
newCharArray[--len] = num % 2 == 0 ? '0' : '1';
flag = num / 2;
}
if (flag == 1) {
newCharArray[0] = '1';
}
if (newCharArray[0] == '1') {
return new String(newCharArray);
}
return new String(newCharArray, 1, a.length());
}