[LeetCode]第八题 :求字符串索引

题目描述:

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

题目解释:

实现strStr()方法。返回needle在haystack中的索引,或者返回-1表示不在haystack中

题目解法:

1.这个其实String早就封装好了indexOf()这个方法就可以求出第二个字符串在第一个字符串中的索引值。当然,出题者肯定想的不是让你用封装的办法写,所以这里还是自己写个实现吧:思路大概就是把String先转成char数组,然后遍历a数组从0到a.length - b.length + 1,然后找是否全部匹配,如果不匹配就继续向后找,匹配则返回索引值i,全部遍历完没有找到则说明没有此子字符串,代码如下:

class Solution {
    public int strStr(String haystack, String needle) {
        char[] a = haystack.toCharArray();
        char[] b = needle.toCharArray();
        if(a.length < b.length) return -1;
        if(a.length == 0 && b.length == 0) return 0;
        if(b.length == 0) return 0;
        for(int i = 0; i < a.length - b.length + 1;i++) {
            if(a[i] == b[0]) {
                boolean flag = true;
                for(int j = 0; j < b.length;j++) {
                    if(a[i + j] != b[j]) {
                        flag = false;
                        break;
                    }
                }
                if(flag) return i;
            }
        }
        return -1;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值