首页 > 其他 > 详细

字符串匹配

时间:2020-06-18 11:49:34      阅读:69      评论:0      收藏:0      [点我收藏+]

字符串匹配问题是很经典的问题,在此详细记录一下各种方法。(Java实现)LeetCode28

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

 

一,暴力

//1.substring
class
Solution { public int strStr(String haystack, String needle) { int h = haystack.length(); int n = needle.length(); for (int i = 0; i <= h - n; i++) { if (haystack.substring(i, i + n).equals(needle)) return i; } return -1; } }

 

//2.indexOf
public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
}

/**
  indexOf源码:(找到首字母后双指针)
   * @param   source       the characters being searched.      haystack底层数组
     * @param   sourceOffset offset of the source string.       0
     * @param   sourceCount  count of the source string.       haystack.length()
     * @param   target       the characters being searched for.   needle
     * @param   targetOffset offset of the target string.      0
     * @param   targetCount  count of the target string.       needle.length()
     * @param   fromIndex    the index to begin searching from.   0 
*/
//先在source中找到首字母与target相同的index。再用双指针判定,如果指到末尾则完全匹配,返回索引,
//否则回溯source下一个字符。(
只保留重要部分)
static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

 

二,

 

 

 

 

t

字符串匹配

原文:https://www.cnblogs.com/faded828x/p/13156549.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!