LeetCode第二十八题-判断字符串是否包含子字符串

Implement strStr()

问题简介:实现方法strStr()
返回字符串haystack中第一次出现符合规则needle的索引,如果不包含这个规则字符串,则返回-1
举例:
1:
输入: haystack = “hello”, needle = “ll”
输出: 2
2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1

如果这道题可以用正则表达式就会很轻松,可是leetcode里不支持

class Solution {
    public int strStr(String haystack, String needle) {
         String regex = needle;
         Pattern pattern = Pattern.compile(regex);
         Matcher matcher = pattern.matcher(haystack);
         if(matcher.find())
         return matcher.start();
         else return -1;
         }
         }

解法一:
将给定字符串haystack遍历到第hsLength - ndLength + 1个值,这是一个临界点,再往后剩余字符串长度小于needle的长度,也就没必要遍历了,用substring()方法截取与needle等长的字符串,两者比较,有相等的结果返回索引,没有返回-1

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

复杂度分析:
时间复杂度:o(n) 一层遍历
空间复杂度:o(n) 在一层遍历中定义n个字符串空间
注:
1.String的substring()方法中,第二个s是小写,取值范围是[0,n)左闭右开
2.String类中equals()已经被重写,可以用来判断字符串内容是否相等

小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值