LeetCode-Java-884. Uncommon Words from Two Sentences

53 篇文章 0 订阅
53 篇文章 0 订阅

题目

We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.)

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Return a list of all uncommon words. 

You may return the list in any order.



Example 1:

Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]
Example 2:

Input: A = "apple apple", B = "banana"
Output: ["banana"]


Note:

0 <= A.length <= 200
0 <= B.length <= 200
A and B both contain only spaces and lowercase letters.

代码

此题需要注意的是将数组转化为ArrayList,通过List作为桥梁。
如果不转化为ArrayList,在调用add方法的时候会抛出java.lang.UnsupportedOperationException异常,因为List并未实现add方法调用的为AbstractList的add方法

class Solution {
    public String[] uncommonFromSentences(String A, String B) {
        String[] AWords = A.split(" ");
        String[] BWords = B.split(" ");

        List<String> AList1 = Arrays.asList(AWords);
        List<String> BList1 = Arrays.asList(BWords);

        ArrayList<String> AList = new ArrayList<String>(AList1);
        ArrayList<String> BList = new ArrayList<String>(BList1);

        String[] result = new String[400];
        int j=0;


        int len1 = AList.size();
        for(int i = 0;i<len1;i++){
            String temp = AList.get(i);
            AList.remove(temp);
            if(!BList.contains(temp)&&!AList.contains(temp)){
                result[j++] = temp;
            }
            AList.add(i,temp);
        }


        int len = BList.size();
        for(int i = 0;i<len;i++){
            String temp = BList.get(i);
            BList.remove(temp);
            if(!AList.contains(temp)&&!BList.contains(temp)){
                result[j++] = temp;
            }
            BList.add(i,temp);
        }



        return Arrays.copyOf(result,j);
    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值