java - How to search for a pattern within a String/Char array? -
i need pattern in input given user. , return (start,end)position if found.
eg:-
input = a b c d b c d
pattern = d c a
output = 3,6
the pattern need not occur consecutively.
it can d @ start of input, c @ middle , @ end. - valid scenario.
two things confused about.
how take input? array? if yes, string or char array?
how pattern?
the format of input not matter here: can take both string , sequence strings. trick deciding on algorithm use solve problem.
in case, greedy strategy work:
- read 2 strings,
s
(string) ,p
(pattern). - make 2 indexes -
si
string, ,pi
pattern, , set them both zero. - search letter
p.charat(pi)
ins
starting @si
. if letter cannot found in substringsi
end, pattern not exist - otherwise, take first occurrence of
p.charat(pi)
ins
, setsi
index plus one, , advancepi
one. - if reach end of
p
, done - otherwise, go search step, , continue processing until either find pattern, or exhaust string.
- if need print indexes sequence, add array of indexes, , fill out go. length of array should equal length of
p
.
note there may multiple solutions problem. when solution exists, algorithm finds first "lexicographic" set of indexes solve problem.
Comments
Post a Comment