Sorting Strings and extracting common elements of two String arrays in Java

前端 未结 8 1112
南方客
南方客 2020-12-22 12:01

I was asked to write down a Java function sharedStr that by given 2 sorted arrays of Strings, returns the number of Strings that appea

8条回答
  •  臣服心动
    2020-12-22 12:16

    Because the arrays are sorted, you can step through them knowing you're walking them in order.

    import java.util.List;
    import java.util.LinkedList;
    class StringTest {
        static List sharedStrings(String[] a, String[] b) {
            List result = new LinkedList();
            int apos = 0;
            int bpos = 0;
            while(!(apos == a.length || bpos == b.length)) {
                int comp = a[apos].compareTo(b[bpos]);
                if(comp == 0) result.add(a[apos++]);
                else if(comp > 0) bpos++;
                else apos++;
            }
            return result;
        }
        public static void main(String[] args) {
            String[] a = new String[]{"this","is","a","test"};
            String[] b = new String[]{"test","for","a","party"};
    
            java.util.Arrays.sort(a);
            java.util.Arrays.sort(b);
    
            List result = sharedStrings(a,b);
            for(String s : result) System.out.println(s);
    
        }
    }
    

提交回复
热议问题