Leetcode:28. Implement strStr()(JAVA)

来源:互联网 发布:java读取配置文件参数 编辑:程序博客网 时间:2024/05/29 08:35

【问题描述】

Implement strStr().

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

【思路】

本题的目的其实是实现函数String.indexof()

即:return haystack.indexOf(needle);

维护两个指针,依次扫描haystack与needle。

【code】

public class Solution {    public int strStr(String haystack, String needle) {        //return haystack.indexOf(needle);if (haystack.length() < needle.length()) {return -1;}if (needle.length() == 0) {return 0;}if (haystack.length() == 0) {return -1;}for (int i = 0; i <= haystack.length() - needle.length(); i++) {if (haystack.charAt(i) == needle.charAt(0)) {int j = 0;for (j = 0; j < needle.length(); j++) {if (haystack.charAt(i + j) != needle.charAt(j)) {break;}}if (j != needle.length()) {continue;} else {return i;}}}return -1;    }}




0 0
原创粉丝点击