LintCode 13. 字符串查找

LintCode 13. 字符串查找

问题描述

对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
样例
如果 source = “source” 和 target = “target”,返回 -1。
如果 source = “abcdabcdefg” 和 target = “bcd”,返回 1。

问题分析

最简单的做法就是暴力做法,从主串的第一个位置,将子串和主串对应长度的子串比较,不一样就将主串下一个字符当做开始位置,依次比较,这里我选择了效率很高的一种算法–Sunday,Sunday算法的高效在于有效的避免了一些不必要的比较,在字符串模式匹配中超越BF、KMP和BM的算法

代码
class Solution {
public:
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
     */
    int strStr(const char *source, const char *target) {
        // write your code here
        if(source == NULL || target == NULL)
            return -1;
        int slen = strlen(source);
        int tlen = strlen(target);

        if(slen == 0 && tlen == 0)
            return 0;
        int next[256];
        for (int i = 0; i < 256; i++) {
            next[i] = -1;
        }
        for (int i =0; i < tlen; i++) {
            next[target[i]] = i;
        }

        for (int i = 0; i <= slen - tlen;) {
            int j = i;
            int k = 0;
            for(;k < tlen && j < slen && source[j] == target[k];j++,k++);
            if(k == tlen)
                return i;
            else {
                if(i+tlen < slen)
                    i += (tlen - next[source[i+tlen]]);
                else
                    return -1;
            }
        }
        return -1;
    }
};
代码思路

比较难理解的是这条语句 i += (tlen - next[source[i+tlen]]);,这条语句的主要作用是找到子串需要进行的偏移量。下面的链接有具体的说明。

参考链接 http://blog.csdn.net/laojiu_/article/details/50767615

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值