250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Implement strStr() 본문
728x90
반응형
28. Implement strStr()
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.
주어진 haystack 문자열 내에서 needle 문자를 찾아, 시작되는 인덱스를 리턴하면 된다.
예외로 needle이 ""로 주어진다면 그냥 0을 리턴하도록 했다.
needle이 공백이 아니라면 for문을 이용해 haystack을 needle의 크기만큼 잘라서 비교하면 된다.
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle == ""){
return 0;
}
int len = needle.size();
int answer = -1;
for(int i = 0; i < haystack.size(); i++){
string current = haystack.substr(i, len);
if(current == needle){
answer = i;
break;
}
}
return answer;
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Maximum Subarray (0) | 2021.07.08 |
---|---|
(Leet Code c++)Search Insert Position (0) | 2021.07.07 |
(Leet Code c++)Remove Element (0) | 2021.07.07 |
(Leet Code c++)Remove Duplicates from Sorted Array (0) | 2021.07.07 |
(Leet Code c++)Merge Two Sorted Lists (0) | 2021.07.07 |