drz5553 2012-11-12 18:38
浏览 15

在字符串中搜索模式

Pattern search within a string.

for eg.

$string = "111111110000";
FindOut($string);

Function should return 0

function FindOut($str){    
    $items =  str_split($str, 3);    
    print_r($items);
}
  • 写回答

5条回答 默认 最新

  • 普通网友 2012-11-12 18:52
    关注

    What you have here can conceptually be solved with a sliding window. For your example, you have a sliding window of size 3.

    For each character in the string, you take the substring of the current character and the next two characters as the current pattern. You then slide the window up one position, and check if the remainder of the string has what the current pattern contains. If it does, you return the current index. If not, you repeat.

    Example:

    1010101101
    |-|
    

    So, pattern = 101. Now, we advance the sliding window by one character:

    1010101101
     |-|
    

    And see if the rest of the string has 101, checking every combination of 3 characters.

    Conceptually, this should be all you need to solve this problem.

    Edit: I really don't like when people just ask for code, but since this seemed to be an interesting problem, here is my implementation of the above algorithm, which allows for the window size to vary (instead of being fixed at 3, the function is only briefly tested and omits obvious error checking):

    function findPattern( $str, $window_size = 3) {
        // Start the index at 0 (beginning of the string)
        $i = 0;
    
        // while( (the current pattern in the window) is not empty / false)
        while( ($current_pattern = substr( $str, $i, $window_size)) != false) {
            $possible_matches = array();
    
            // Get the combination of all possible matches from the remainder of the string
            for( $j = 0; $j < $window_size; $j++) {
                $possible_matches = array_merge( $possible_matches, str_split( substr( $str, $i + 1 + $j), $window_size));
            }
    
            // If the current pattern is in the possible matches, we found a duplicate, return the index of the first occurrence
            if( in_array( $current_pattern, $possible_matches)) {
                return $i;
            }
    
            // Otherwise, increment $i and grab a new window
            $i++;
        }
        // No duplicates were found, return -1
        return -1;
    }
    

    It should be noted that this certainly isn't the most efficient algorithm or implementation, but it should help clarify the problem and give a straightforward example on how to solve it.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看