dongshan9619 2019-08-01 07:25
浏览 29
已采纳

如何在混乱的字母中找到一个字符串

I need to write a program to find a word in jumbled letters.For eg:Consider the string $example = "ahwerlyp"; I need to find the word help from the string.How can i Find it.Any help would be appreciated.

I have tried to use substr() function but it only return the string.if it is all in same line,otherwise it return zero

<?php
$example = "ahwerlyp";
$findword = "help";
/**how to find the word help from it**/


 if($findword is present in $example)
{
echo "exists";
}

?>
  • 写回答

2条回答 默认 最新

  • duanbo6871 2019-08-01 08:46
    关注
    1. Split each word into an array containing all the individual letters. (Can be done for example using preg_split('//u', 'word', -1, PREG_SPLIT_NO_EMPTY))

    2. For each word, count how many times each letter occurs - array_count_values gives you an array with the input array values (our individual letters) as keys, and the count as value.

    3. Loop over the counted letters from the second word, and check if the count of the same letter in the first word is greater or equal at least. If that is not the case for any of the letters from the second word, it is not “contained” in the first one.

    Let’s wrap all that into a nice little function, and we get the following:

    function does_a_contain_b($a, $b) {
      // split both words into individual letters, and count their occurrences
      $letters_given  = array_count_values(preg_split('//u', $a, -1, PREG_SPLIT_NO_EMPTY));
      $letters_needed = array_count_values(preg_split('//u', $b, -1, PREG_SPLIT_NO_EMPTY));
    
      // we assume b is going to be contained in a for now
      $contained = true;
    
      foreach($letters_needed as $letter => $count) {
        // if the letter from 2nd word does not occur in the 1st one at all,
        // or the count in 2nd is not at least equal to that of 1st,
        // we set our flag to false, and break out of the loop
        if(!isset($letters_given[$letter]) || $letters_given[$letter] < $count) {
          $contained = false;
          break;
        }
      }
      return $contained;
    }
    
    // a couple of test cases
    var_dump(
      does_a_contain_b('ahwerlyp', 'help'),  // true
      does_a_contain_b('ahwerlyp', 'hhelp'), // false
      does_a_contain_b('ahwerlyp', 'hype'),  // true
      does_a_contain_b('ahwerlyp', 'foobar') // false
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?