【Lintcode】684. Missing String

题目地址:

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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值