LeetCode-Implement strStr()
Description:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
题意:实现字符串函数strStr()的功能,返回字符串haystack第一次出现字符串needle的位置,如果没有则返回-1;对于needle字符串为空的情况则返回0;
解法:只要遍历字符串haystack,每次计算其长度为needle.length()的字串是否和needle相等即可;
Javaclass Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
if (needle.length() > haystack.length()) return -1;
int len = needle.length();
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
while (i < haystack.length() && haystack.charAt(i) != needle.charAt(0)) i++;
if (i > haystack.length() - needle.length()) break;
if (needle.equals(haystack.substring(i, i + needle.length()))) return i;
}
return -1;
}
}
版权声明
本文仅代表作者观点,不代表博信信息网立场。