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) in s starting @ si. if letter cannot found in substring si end, pattern not exist
  • otherwise, take first occurrence of p.charat(pi) in s, set si index plus one, , advance pi 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

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -