How to compare a string with another where the one has space in between

后端 未结 4 1259
挽巷
挽巷 2021-01-13 05:04

How do I compare these two string :

val a = \"fit bit versa\"
val b = \"fitbit\"

another example

val a = \"go pro hero 6\"
         


        
4条回答
  •  悲哀的现实
    2021-01-13 05:30

    I think this is a solution to your problem.

    def matchPattern(a: String, b: String): Boolean =
      a
        .split("\\s+")
        .tails
        .flatMap(_.inits)
        .exists(_.mkString("") == b)
    

    This will check for any word or sequence of words in a that exactly matches the word in b. It will reject cases where b is embedded in a longer word or sequence of words.

    The split call turns the string into a list of words.

    The tails call returns all the possible trailing sub-sequences of a list, and inits returns all the leading sub-sequences. Combining the two generates all possible sub-sequences of the original list.

    The exist call joins the words together and compares them with the test word.


    Note that tails and inits are lazy, so they will generate each solution to be tested in turn, and stop as soon as a solution is found. This is in contrast to the solutions using sliding which create every possible combination before checking any of them.

提交回复
热议问题