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()已经被重写,可以用来判断字符串内容是否相等

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

猜你喜欢

转载自blog.csdn.net/weixin_44147866/article/details/89762676