LeetCode 28Implement strStr() 寻找子字符串的下标的位置

来源:互联网 发布:社交网络的利弊 英文 编辑:程序博客网 时间:2024/05/21 08:04

题目要求:
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

题目不难,可以直接使用暴力搜索的方式进行处理

public class solution {    public int strStr(String haystack, String needle) {        //使用暴力搜索的方式进行求解        int l1 = haystack.length();        int l2 = needle.length();        if(l1 == l2 && l1 == 0) return 0;        int j = 0;        for(int i = 0; i <= l1 - l2; i++) {            for(j = 0; j < l2; j++) {                if(haystack.charAt(i + j) != needle.charAt(j)) break;            }            if(j == l2) return i;        }        return -1;    }}
1 0
原创粉丝点击