我不点开评论都知道评论区有多精彩。这不,有网友立马跳出来辟谣:“你们说错了,Boss直聘也凉了好吗?”这语气有点搞笑,但其实很沉重。
这背后反映的就现在招聘市场的真实情况。但无论如何,对于我们来说,能找到一份满意的工作始终是目标。我们能做的就是提升自己,他强任他强,清风拂山岗。
哈希映射统计:首先使用哈希映射(HashMap)统计words数组中每个单词出现的次数。
滑动窗口:由于所有单词的长度相同,我们可以使用滑动窗口的方式,以单词的长度为步长在原字符串s上滑动,检查每个可能的窗口。
匹配验证:对于每个窗口,使用另一个哈希映射统计窗口中每个单词的出现次数,然后与words的哈希映射进行比较,看是否完全匹配。
记录起始位置:如果一个窗口完全匹配,记录该窗口的起始位置。
优化:为了减少不必要的检查,我们只需要在0到wordLength-1的范围内开始滑动窗口,其中wordLength是数组words中单词的长度。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
int wordLength = words[0].length();
int allWordsLength = words.length * wordLength;
Map<String, Integer> wordMap = new HashMap<>();
List<Integer> result = new ArrayList<>();
for (String word : words) {
wordMap.put(word, wordMap.getOrDefault(word, 0) + 1);
}
for (int i = 0; i < wordLength; i++) {
for (int j = i; j <= s.length() - allWordsLength; j += wordLength) {
Map<String, Integer> seen = new HashMap<>();
int k = 0;
while (k < words.length) {
String word = s.substring(j + k * wordLength, j + (k + 1) * wordLength);
if (wordMap.containsKey(word)) {
seen.put(word, seen.getOrDefault(word, 0) + 1);
if (seen.get(word) > wordMap.get(word)) break;
} else {
break;
}
k++;
}
if (k == words.length) result.add(j);
}
}
return result;
}
}
function findSubstring(s, words) {
const wordLength = words[0].length;
const allWordsLength = words.length * wordLength;
const wordMap = new Map();
const result = [];
words.forEach(word => {
wordMap.set(word, (wordMap.get(word) || 0) + 1);
});
for (let i = 0; i < wordLength; i++) {
for (let j = i; j <= s.length - allWordsLength; j += wordLength) {
const seen = new Map();
let k = 0;
while (k < words.length) {
const word = s.substr(j + k * wordLength, wordLength);
if (wordMap.has(word)) {
seen.set(word, (seen.get(word) || 0) + 1);
if (seen.get(word) > wordMap.get(word)) break;
} else {
break;
}
k++;
}
if (k === words.length) result.push(j);
}
}
return result;
}
package main
import "fmt"
func findSubstring(s string, words []string) []int {
wordLength := len(words[0])
allWordsLength := len(words) * wordLength
wordMap := make(map[string]int)
var result []int
for _, word := range words {
wordMap[word]++
}
for i := 0; i < wordLength; i++ {
for j := i; j <= len(s)-allWordsLength; j += wordLength {
seen := make(map[string]int)
var k int
for k = 0; k < len(words); k++ {
word := s[j+k*wordLength : j+(k+1)*wordLength]
if count, exists := wordMap[word]; exists {
seen[word]++
if seen[word] > count {
break
}
} else {
break
}
}
if k == len(words) {
result = append(result, j)
}
}
}
return result
}
以s = "barfoothefoobarman", words = ["foo","bar"]为例,我们的函数应该返回[0,9]。这是因为在s中,从索引0开始的子串"barfoo"和从索引9开始的子串"foobar"恰好由words中的所有单词串联形成。
对编程、职场感兴趣的同学,可以链接我,微信:coder301 拉你进入“程序员交流群”。