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条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了