Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/885/
class Solution {
public int strStr(String haystack, String needle) {
if (haystack.length() == needle.length())
return haystack.equals(needle) ? 0 : -1;
if (haystack.length() < needle.length())
return -1;
// You don't need to use contains() library since it is overlapped!
int i = 0, j = 0;
int start = 0;
int count = 0;
while (i < haystack.length() && j < needle.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
count++;
} else { //initialize
start++;
i = start;
j = 0;
count = 0;
}
if (count == needle.length()) return start;
}
return -1;
}
}
좀 더 모듈화하고, 간단하게 구현할 수 있다.
class Solution {
public int strStr(String haystack, String needle) {
if (haystack.length() == needle.length())
return haystack.equals(needle) ? 0 : -1;
if (haystack.length() < needle.length())
return -1;
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
if (compare(haystack, i, needle)) return i;
}
return -1;
}
private boolean compare(String haystack, int startIndex, String needle) {
for (int i = 0; i < needle.length(); i++) {
int index = startIndex + i;
if (haystack.charAt(index) != needle.charAt(index)) {
return false;
}
}
return true;
}
}
엄청 간단한 것 중엔 이런 것도 있다;
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle) ;
}
}