1 万人千题,跟着英雄哥有肉吃
https://blog.youkuaiyun.com/WhereIsHeroFrom/article/details/121260397
2 打卡第22讲
《算法零基础100讲》(第22讲) 字符串算法(二) - 字符串比较
https://blog.youkuaiyun.com/WhereIsHeroFrom/article/details/120875787
3 题目
3.1 剑指 Offer 05. 替换空格
如此水题解,有些羞愧
class Solution {
public String replaceSpace(String s) {
return s.replaceAll(" ","%20");
}
}
3.2 面试题 10.05. 稀疏数组搜索
二分查找还是不熟练,需要练练
class Solution {
public int findString(String[] words, String s) {
return search(words, s, 0, words.length-1);
}
public int search(String[] words, String s, int l, int r) {
if (l >= r) {
if (words[l].equals(s)) {
return l;
} else {
return -1;
}
}
int mid = (r + l) / 2;
int index = mid;
while (index > 0 && words[index].length() == 0) {
index--;
}
if (index == 0 && words[index].length() == 0) {
return search(words, s, mid + 1, r);
}
if (words[index].equals(s)) {
return index;
}
if (words[index].compareTo(s) > 0) {
return search(words, s, l, mid - 1);
} else if (words[index].compareTo(s) < 0) {
return search(words, s, mid + 1, r);
}
return -1;
}
}
3.3 290. 单词规律
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) {
return false;
}
Map<Character, String> map = new HashMap<>();
Map<String, Character> map2 = new HashMap<>();
for (int i = 0; i < words.length; i++) {
char c = pattern.charAt(i);
String record = map.get(c);
Character p = map2.get(words[i]);
if (record == null && p == null) {
map.put(c, words[i]);
map2.put(words[i], c);
continue;
}
if (p == null || p != c) {
return false;
}
if (!words[i].equals(map.get(c))) {
return false;
}
}
return true;
}
}
3.4 1309. 解码字母到整数映射
public String freqAlphabets(String s) {
char[] chars = {'0', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z'
};
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.length()) {
if (i >= s.length()) {
break;
}
if (i + 2 < s.length() && s.charAt(i + 2) == '#') {
char[] charNum = {s.charAt(i), s.charAt(i + 1)};
int num = Integer.valueOf(String.valueOf(charNum));
sb.append(chars[num]);
i += 3;
} else {
int num = s.charAt(i) - '1' + 1;
sb.append(chars[num]);
i++;
}
}
return sb.toString();
}
3.5 1967. 作为子字符串出现在单词中的字符串数目
又水一道,逃
class Solution {
public int numOfStrings(String[] patterns, String word) {
if (patterns.length == 0) {
return 0;
}
int count = 0;
for (String p : patterns) {
if (word.contains(p)) {
count++;
}
}
return count;
}
}