[leetcode]28. Implement strStr()(Java)

来源:互联网 发布:视频展示台软件 编辑:程序博客网 时间:2024/06/05 07:04

https://leetcode.com/problems/implement-strstr/#/description


Implement strStr().

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



package go.jacob.day719;/** * 28. Implement strStr() *  * @author Jacob 题意是:判断needle是否为haystack的子串 */public class Demo4 {/* * 判断needle是否为haystack的子串,是则返回第一个index,否则返回-1; */public int strStr(String haystack, String needle) {if (haystack == null || needle == null || haystack.length() < needle.length())return -1;if (needle.length() == 0)return 0;for (int i = 0; i <= haystack.length() - needle.length(); i++) {if (haystack.substring(i, i + needle.length()).equals(needle))return i;}return -1;}/* * 牛客网解答 */public String strStr_niuke(String haystack, String needle) {if (haystack == null || needle == null || haystack.length() < needle.length())return null;if (needle.length() == 0)return haystack.substring(0);for (int i = 0; i <= haystack.length() - needle.length(); i++) {for (int j = 0; j < needle.length(); j++) {if (haystack.substring(i, i + needle.length()).equals(needle))return haystack.substring(i);}}return null;}}