[LeetCode] 28. Find the Index of the First Occurrence in a String with java
Problem
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
.
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().
Example 1:
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.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
1 <= haystack.length, needle.length <= 10^4
haystack
andneedle
consist of only lowercase English characters.
Solution
class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
if (haystack.substring(i, i + needle.length()).equals(needle) == true)
return i;
} return -1;
}
}
Explanation
- 문자열 needle이 문자열 haystack속 어딘가에 포함되는지 알아보기 위한 if 조건문을 다음과 같이 작성할 수 있다.
if (haystack.substring(시작index, 종료 index).equals(needle) retrun 시작index;
- 문자열 haystack의 첫 인덱스인 0부터 인덱스를 증가시키면서 문자열 needle의 포함 여부를 확인해야 하기위해 for 반복문을 작성한다.
- 문자열 haystack의 인덱스를 끝가지 증가시켜 비교할 필요는 없기 때문에 변수 i의 조건식을 문자열 haystack의 길이가 아닌 문자열 haystack의 길이에서 문자열 needle의 길이를 빼주고, 1을 더한 값으로 작성한다.
- for 반복문을 빠져나오면 문자열 needle이 문자열 haystack에 포함되지 않는다는 의미가 되므로 -1을 반환한다.
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) { if (haystack.substring(i, i + needle.length()).equals(need== true) return i; } return -1;
Leave a comment