Implement strStr().
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 = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
Example 3:
Input: haystack = "", needle = "" Output: 0
Constraints:
- 0 <= haystack.length, needle.length <= 5 * 104
- haystack and needle consist of only lower-case English characters.
문제 풀이:
c언어에 문자열을 검색하는 strstr라는 함수가 있다는 걸 알게 되었다.
브루트포스로 풀었다.
class Solution {
public:
int strStr(string haystack, string needle) {
int m = needle.length();
int n = haystack.length();
if(m==0){
return 0;
}
if(n<m){
return -1;
}
int result = -1;
for(int i=0; i<n; i++){
if(haystack[i] == needle[0]){
result = i;
for(int j=1; j<m; j++){
if(haystack[i+j] != needle[j]){
result = -1;
break;
}
}
if(result > -1){
return result;
}
}
}
return result;
}
};
++ 더 빠른 코드
class Solution {
public:
int strStr(string haystack, string needle) {
int m = needle.length();
int n = haystack.length();
if(m==0){
return 0;
}
if(n<m){
return -1;
}
int result = -1;
for(int i=0; i<=n-m; i++){
result = i;
for(int j=0; j<m; j++){
if(haystack[i+j] != needle[j]){
result = -1;
break;
}
}
if(result > -1){
return i;
}
}
return result;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 23] Merge k Sorted Lists (0) | 2020.11.12 |
---|---|
[leetcode 54] Spiral Matrix (0) | 2020.11.10 |
[leetcode 42] Trapping Rain Water (0) | 2020.11.10 |
[leetcode 48] Rotate Image (0) | 2020.11.09 |
[leetcode 412] Fizz Buzz (0) | 2020.11.09 |
댓글