题目地址:
https://www.lintcode.com/problem/missing-string/description
给定两个字符串 s 1 s_1 s1和 s 2 s_2 s2,都是由空格分隔的英文单词组成的。问 s 1 s_1 s1中有哪些单词是 s 2 s_2 s2中没有出现过的。要求返回结果保持单词在 s 1 s_1 s1中出现的顺序。
可以用一个哈希表存 s 2 s_2 s2中的所有单词,然后遍历 s 1 s_1 s1中的单词,如果不在哈希表里则加入最后的结果中。代码如下:
import java.util.*;
public class Solution {
/**
* @param str1: a given string
* @param str2: another given string
* @return: An array of missing string
*/
public List<String> missingString(String str1, String str2) {
// Write your code here
Set<String> set = new HashSet<>(Arrays.asList(str2.split(" ")));
List<String> res = new ArrayList<>();
for (String s : str1.split(" ")) {
if (!set.contains(s)) {
res.add(s);
}
}
return res;
}
}
时间复杂度 O ( s 1 . l e n g t h ( ) + s 2 . l e n g t h ( ) ) O(s_1.length()+s_2.length()) O(s1.length()+s2.length()),空间 O ( s 2 . l e n g t h ( ) ) O(s_2.length()) O(s2.length())。