leetcode28. Implement strStr()

来源:互联网 发布:图像阈值分割算法 编辑:程序博客网 时间:2024/05/17 23:54

28. Implement strStr()

Implement strStr().

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) {        if (haystack == null || needle == null) {            return -1;        }        int i, j;        for (i = 0; i < haystack.length() - needle.length() + 1; i++) {            for (j = 0; j < needle.length(); j++) {                if (haystack.charAt(i + j) != needle.charAt(j)) {                   break;                }            }            if (j == needle.length()) {                return i;            }        }        return -1;        }}

这里写图片描述

0 0