admin管理员组文章数量:1636896
https://leetcode/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;
}
}
本文标签: LeetCodeimplementJavastrStr
版权声明:本文标题:[leetcode]28. Implement strStr()(Java) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729234678a1191858.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论