[LeetCode] Implement strStr()

来源:互联网 发布:bluecloud 新域名 编辑:程序博客网 时间:2024/05/25 18:12

题目

Implement strStr().

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

思路

按照下标递增的顺序比较haystack中的所有子字符串和needle。

代码

public class Solution {    public int strStr(String haystack, String needle) {        if(needle.equals(""))            return 0;                int len1 = haystack.length();        int len2 = needle.length();                for(int beginIndex = 0; beginIndex <= len1 - len2; beginIndex++) {            int i = beginIndex;            int j = 0;                        while(j != len2 && haystack.charAt(i) == needle.charAt(j)) {                i++;                j++;            }                        if(j == len2)                return beginIndex;        }        return -1;    }}

0 0
原创粉丝点击