https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description
Q. 주어진 문자열 haystack에서 needle이 등장하는 첫번째 index를 반환하라.
Solution.
haystack.IndexOf(needle);
를 사용하면 한번에 찾아 질 것이다.
그렇지만, 로직대로 만들어 보면,
needle과 같은 문자로 haystack이 시작하면 그 뒤로 끝까지 같나 확인 한다.
도중에 index 범위체크등을 넣어 준다.
더보기
public int StrStr(string haystack, string needle)
{
if(haystack.Length < needle.Length)
return -1;
for(int q = 0; q < haystack.Length; ++q)
{
char cur = haystack[q];
if(cur != needle[0]) continue;
bool match = true;
for(int k = 0; k < needle.Length; ++k)
{
if(q+k>=haystack.Length || (q+k<haystack.Length && haystack[q+k]!=needle[k]))
{
match = false;
break;
}
}
if(match) return q;
}
return -1;
}
결과.
'Leetcode > Top Interview 150' 카테고리의 다른 글
[Two Pointers][Easy] 125. Valid Palindrome (0) | 2024.05.03 |
---|---|
[Array/String][Hard] 68. Text Justification (0) | 2024.05.03 |
[Array/String][Medium] 6. Zigzag Conversion. (0) | 2024.05.02 |
[Array/String][Easy] 14. Longest Common Prefix (0) | 2024.05.01 |
[Array/String][Easy] 58. Length of Last Word (0) | 2024.05.01 |