查找目标字符串

一、前言

从模式串中查找目标串的首字母下标,不存在则返回-1

二、算法思路

方法一:暴力求解
宽度为目标串长度的窗口从左向右移动,判断窗口内的每个字符是否与目标串对应的字符相等,若不相等则窗口右移一格,重复之前的操作。
在这里插入图片描述

方法二:Robin Karp算法
将字符串转换成R进制的数(其中R为素数,素数哈希冲突的可能性小),利用哈希函数的特征,如果哈希值不同则字符串一定不相等,如果哈希值相同,则字符串可能相等。hash函数采用除留取余的方式。

三、算法Java实现

方法一:暴力求解

public class Solution {
    /**
     * @param source: A source string
     * @param target: A target string
     * @return: An integer as index
     */
    public int strStr(String source, String target) {
        //外层循环控制窗口右移
        for (int i = 0; i < source.length() - target.length() + 1; ++i) {
            boolean flag = true;
            //内层循环比较窗口内的字符
            for (int j = 0; j < target.length(); ++j) {
                if(source.charAt(i + j) != target.charAt(j)){
                    flag = false;
                    break;
                }
            }
            if(flag){
                return i;
            }
        }
        return -1;
    }
}

方法二:Robin Karp算法

public class Solution {
    /**
     * @param source: A source string
     * @param target: A target string
     * @return: An integer as index
     */
    public int strStr(String source, String target) {
        if(source == null || target == null){
            return -1;
        }
        if(source.length() < target.length()){
            return -1;
        }
        if(target.length() == 0){
            return 0;
        }
        int R = 31, Q=10000000;
        int power=1;
        //计算R的target.length()次方 取余防止溢出
        for (int i = 0; i < target.length(); i++) {
            power = (power * R) % Q;
        }
        //R进制计算公式:a0 + a1*R + a2*R^2 + ... + an*R^n
        //将目标串转换为R进制数的hash值
        int targetHash = 0;
        for (int i = 0; i < target.length(); i++) {
            targetHash = (targetHash * R + target.charAt(i)) % Q;
        }
        //计算各子串的hash值
        int sourceHash = 0;
        for (int i = 0; i < source.length(); i++) {
            sourceHash = (sourceHash * R + source.charAt(i)) % Q;
            if(i < target.length() - 1){
                continue;
            }
            if(i > target.length() - 1){
                sourceHash = sourceHash - (source.charAt(i - target.length()) * power) % Q;
            }
            if(sourceHash < 0){
                sourceHash += Q;
            }
            if(targetHash == sourceHash && target.equals(source.substring(i - target.length() + 1, i + 1))){
                return i - target.length() + 1;
            }
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值