문제
주어진 문자열 haystack과 needle이 있을 때,
needle이 haystack 내에서 처음 나타나는 위치를 반환합니다.
needle이 존재하지 않으면 -1을 반환합니다.
조건
예제 2
입력: haystack = "leetcode", needle = "leeto"
출력: -1
해결
딱히 막힌건 없었고 남은 haystack의 길이를 체크했어야 하는걸 유의하면 될것같다.
indexOf 라는 함수를 처음 알게되었다..
class Solution {
int strStr(String haystack, String needle) {
for (int i = 0; i <= haystack.length - needle.length; i++) {
int t = i + needle.length;
if (haystack.substring(i, t) == needle) {
return i;
}
}
return -1;
}
}
class Solution {
int strStr(String haystack, String needle) {
if (haystack.length == needle.length){
if(haystack==needle){
return 0;
}else{
return -1;
}
}else{
for (var i = 0; i < haystack.length; i++) {
if (needle.length == 1) {
if (haystack[i] == needle) {
return i;
}
} else {
if (((i + (needle.length)) <= haystack.length) &&
(haystack.substring(i, (i + (needle.length))) == needle)) {
return i;
}
}
}
}
return -1;
}
}