OA题目differentKSubStrings [array]

Employ two hashset to remove duplicates.

1st for remove (or prevent) duplicate substrings

2nd for remove the duplicate chars .

Time:

O(n) forloop * O(k) every time iterate k times + O(n) iterate n times = O(n*k)

Space:

O(n) set + O(k) set + O(n) array = O(n)

knowledge:
1 create new object in a loop.
every time it create a new object, the variable have a reference to it.
2 iterator
while(it.hasNext()) {
it.next();
}
hasNext() if the iterator has more elements
next() return the next element

Trick:
to iterator a array/string, sometimes we need to do process on k substring/subarray.
The start pointer is i and the end pointer is i + j ( j from 0 to k - 1). It has two loops in common
Always remember to add another i + j < a.length in the condition part.
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < k; j++ ) { xx

}
}


public class differentKSubStrings {
    public static void diffKSubStrings(String str, int k) {
        List ret = new ArrayList<>();
        HashSet str_set = new HashSet<>();


        for (int i = 0; i < str.length() - k; i ++) {
            HashSet ch_set = new HashSet<>();    //  ??  every time it creates a new Object or once we created, ignore it.

            for (int j = 0; j < k && i + j < str.length(); j++) {   //  !! remember inside the loop ,add and notice it's not && j < str.length()
                if (ch_set.contains(str.charAt(i + j))) {
                    break;
                }
                ch_set.add(str.charAt(i + j));
            }

            if (ch_set.size() == k) {
                str_set.add(str.substring(i, i + k));
            }

            ch_set.clear();
        }

        //  add element in set to the arraylist
        Iterator iterator = str_set.iterator();

        while (iterator.hasNext()) {
            ret.add(iterator.next());   //  Iterator 的实现
        }

        //  print ret
        for (String item : ret) {
            System.out.println(item);
        }

        return;
    }


    public static void main(String[] args) {
        diffKSubStrings("awaglknagawybagwkwagl", 4);
    }
}

你可能感兴趣的:(OA题目differentKSubStrings [array])