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

前端 未结 8 1023
南方客
南方客 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:11

    Go with the assumption that the two lists are sorted before entering your sharedStr algorithm. You'd want to keep two references: each to an element in each of the two lists.

    Then you'd start comparing element after element and progress either or both of the references accordingly. Here's a pseudo-code:

    def sharedStr(lista, listb):
        indexa = indexb = 0
        shared = 0
    
        while 1:
            try:
                a = lista[indexa]
                b = listb[indexb]
            except IndexError:     # we fell off one of the lists
                break
    
            if a == b:
                shared += 1
                indexa += 1
                indexb += 1
            elif a < b:
                indexa += 1
            else:    # b < a
                indexb += 1
    
        return shared
    

    Yes, this is also a valid Python code. ;-)

    0 讨论(0)
  • 2020-12-22 12:12
    int x =  0;
    int i= 0;
    int j = 0;
    while(i != list1.length && j != list2.length){
      int v = list1[i].compareTo(list2[j]);
      if (v == 0){
        x++;i++;j++;
      }else if (v < 0){
        i++;
      } else {
        j++;
      }
    }
    return x;
    

    This makes the straightforward assumption that the strings are sorted using String.compareTo which would make sense.

    0 讨论(0)
  • 2020-12-22 12:13
    1. Strings are usually ordered in lexicographic fashion (alphabetical). However, as long as the ordering is consistent, the exact ordering method is not important for this problem (they could be reverse sorted for instance).
    2. Java compares objects (not object references) using .equals() (for boolean) or .compareTo() (for relational comparison) For instance:

    .

    String a = "Hello";
    a.equals("Hello"); // true
    String b = "Not hi";
    b.equals(a); // false
    

    Be careful accidentally using == - for constant strings, due to VM designs, it may actually say two Strings are equal, as they are in fact the same object.

    0 讨论(0)
  • 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<String> sharedStrings(String[] a, String[] b) {
            List<String> result = new LinkedList<String>();
            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<String> result = sharedStrings(a,b);
            for(String s : result) System.out.println(s);
    
        }
    }
    
    0 讨论(0)
  • 2020-12-22 12:17

    The fact that the arrays are sorted is a red herring, it is irrelevant to the solution. Use a Map<String, Integer> Steps:

    1. For each string in the first array do the following:
      1. do a map.get(currentString)
      2. if that is null, do a map.put(currentString, new Integer(0))
    2. For each string in the second array do the following:
      1. do a map.get(currentString)
      2. if that is null, ignore it, it is not a duplicate.
      3. If that is not null, do a map.put(currentString, new Integer(currentInteger.intValue() + 1);
    3. do a map.getKeySet().iterator() and iterate through the keys.
    4. for each key, get the value. The value is the count of strings that are in both arrays.
    0 讨论(0)
  • 2020-12-22 12:26

    What does it mean sorted arrays that contains strings? There isn't any special description of the way it has been sorted. what is the basic ordinary sorting of strings?

    It means the elements in the array are ordered in a natural sequence. For strings this is alphebetical order with lowercase words place before upper case.

    How does one compare between two strings any way?

    By invoking the compareTo method. If it returns 0 they strings are equal, if return < 0 the first string is lower than the second, if return > 0 the firs string is higher than the second.

    As for how to count repetitions linearly see this: comparing strings in java

    0 讨论(0)
提交回复
热议问题