str1 = "spqrstrupvqw" str2 = "sprt" str3 = "q"
We are looking for a minimal substring from str1 that contains all str2 characters (supposedly ordered) , and no characters from str3 ..
i = 1 .. str1.length cursor = 1 .. str2.length
The solution should be in the form of:
str2.first XX .. XX str2.last
So, to check this substring, we use the cursor over str2 , but we also have a restriction on the absence of str3 characters, so we have:
if str3.contain(str1[i]) cursor = 1 else if str1[i] == str2[cursor] cursor++
Goal Verification:
if cursor > str2.length return solution else if i >= str1.length return not-found
And for optimization, you can proceed to the next search option:
look-ahead = { str2[cursor] or { X | X in str3 }}
In case of str2 not ordered :
i = 1 .. str1.length lookup = { X | X in str2 }
The solution should be in the form of:
str2[x] XX .. XX str2[x]
So, to check this substring, we use the str2 checklist, but we also have a restriction on the absence of str3 characters, so we have:
if str3.contain(str1[i]) lookup = { X | X in str2 } else if lookup.contain(str1[i]) lookup.remove(str1[i])
Goal Verification:
if lookup is empty return solution else if i >= str1.length return not-found
And for optimization, you can proceed to the next search option:
look-ahead = {{ X | X in lookup } or { X | X in str3 }}
code
class Solution { private static ArrayList<Character> getCharList (String str) { return Arrays.asList(str.getCharArray()); } private static void findFirst (String a, String b, String c) { int cursor = 0; int start = -1; int end = -1; ArrayList<Character> stream = getCharList(a); ArrayList<Character> lookup = getCharList(b); ArrayList<Character> avoid = getCharList(c); for(Character ch : stream) { if (avoid.contains(ch)) { lookup = getCharList(b); start = -1; end = -1; } else { if (lookup.contains(ch)) { lookup.remove(ch) if (start == -1) start = cursor; end = cursor; } } if (lookup.isEmpty()) break; cursor++; } if (lookup.isEmpty()) { System.out.println(" found at ("+start+":"+end+") "); } else { System.out.println(" not found "); } } }