每日一题做题记录,参考官方和三叶的题解 |
可以将起点根据 当前下标与单词长度的取余结果进行分类,这样就不用频繁的建立新的哈希表和进行单词统计。
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
int sl = s.length(), wl = words.length, ww = words[0].length();
Map<String, Integer> freq = new HashMap<>();
for (String w : words) // 统计每个单词及其出现的次数
freq.put(w, freq.getOrDefault(w, 0) + 1);
List<Integer> res = new ArrayList<>();
for (int i = 0; i < ww; i++) {
Map<String, Integer> win = new HashMap<>(); // 记录当前子串中出现的单词
for (int j = i; j + ww <= sl; j += ww) {
String cur = s.substring(j, j + ww); // 当前单词
win.put(cur, win.getOrDefault(cur, 0) + 1);
if (j >= i + (wl * ww)) { // 长度超了
int idx = j - wl * ww;
String pre = s.substring(idx, idx + ww);
// 删掉第一个单词
if (win.get(pre) == 1)
win.remove(pre);
else
win.put(pre, win.get(pre) - 1);
if (!win.getOrDefault(pre, 0).equals(freq.getOrDefault(pre, 0))) // 单词不同,剪枝
continue;
}
if (!win.getOrDefault(cur, 0).equals(freq.getOrDefault(cur, 0))) // 单词不同,剪枝
continue;
if (win.equals(freq)) // win与freq中单词完全相同
res.add(j - (wl - 1) * ww);
}
}
return res;
}
}
由于字符串长度固定且不超过 30 30 30,假定所有哈希操作均为 O ( 1 ) O(1) O(1)的;
use std::collections::HashMap;
impl Solution {
pub fn find_substring(s: String, words: Vec<String>) -> Vec<i32> {
let mut res = Vec::new();
let (wl, ww, sl) = (words.len(), words[0].len(), s.len());
if sl == 0 || wl == 0 || sl < wl * ww {
return res;
}
let sb = s.as_bytes();
let mut freq = HashMap::with_capacity(ww * 2);
words.into_iter().for_each(|w| *freq.entry(w).or_insert(0) += 1);
(0..=sl - wl * ww).filter(|i| {
let mut win = HashMap::new();
(0..wl).for_each(|j| {
*win.entry(String::from_utf8(sb[(i + j * ww)..(i + (j + 1) * ww)].to_vec()).unwrap()).or_insert(0) += 1;
});
freq == win
}).map(|i| i as i32).collect::<Vec<i32>>()
}
}
由于字符串长度固定且不超过 30 30 30,假定所有哈希操作均为 O ( 1 ) O(1) O(1)的;
【在用例86上卡了,返回了空……没太搞懂为啥,就换了官方的思路】
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
int sl = s.size(), wl = words.size(), ww = words[0].size();
for (int i = 0; i < ww && i + wl * ww <= sl; i++) {
unordered_map<string, int> win;
for (int j = 0; j < wl; j++)
win[s.substr(i + j * ww, ww)]++; // 在窗口内
for (string &w : words) {
if (--win[w] == 0) // 在word内
win.erase(w);
}
for (int k = i; k < sl - wl * ww + 1; k += ww) {
if (k != i) {
string cur = s.substr(k + (wl - 1) * ww, ww);
if (++win[cur] == 0)
win.erase(cur);
cur = s.substr(k - ww, ww);
if (--win[cur] == 0)
win.erase(cur);
}
if(win.empty()) // word中所有单词都在窗口中出现
res.emplace_back(k);
}
}
return res;
}
};
想到了滑动窗口但做起来依然不顺利,长度超了的判断里面那个剪枝没有注意到,还有各种小细节……这个取余枚举开头的操作很巧,要多多思考~
欢迎指正与讨论! |