LeetCode-Java-884. Uncommon Words from Two Sentences

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/qq_38345606/article/details/81806124

题目

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);
    } 
}

猜你喜欢

转载自blog.csdn.net/qq_38345606/article/details/81806124