[LintCode] Missing String

Problem

Given two strings, you have to find the missing string.

Example

Given a string str1 = This is an example
Given another string str2 = is example

Return ["This", "an"]

Solution

public class Solution {
    /*
     * @param : a given string
     * @param : another given string
     * @return: An array of missing string
     */
    public List<String> missingString(String str1, String str2) {
        // Write your code here
        List<String> res = new ArrayList<>();
        String[] s1 = str1.split(" ");
        String[] s2 = str2.split(" ");
        if (s1.length == s2.length) {
            return res;
        }
        //assume s1.length > s2.length
        if (s1.length < s2.length) {
            String[] temp = s1;
            s1 = s2;
            s2 = temp;
        }
        
        Set<String> unique = new HashSet<>();
        
        //save the short string array in hashset
        for (String s: s2) {
            unique.add(s);
        }
        
        //check the long string array and put the missing strings in result
        for (String s: s1) {
            if (!unique.contains(s)) {
                res.add(s);
            }
        }
        
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值