문제링크: leetcode.com/problems/implement-strstr/
Implement strStr() - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제요약: 문자열이 2개 주어진다. (haystack, needle) haystack문자열 중에서 needle과 일치하는 첫번째 index를 반환하시오. 없다면 -1 반환.
예: haystack: hello, needle: ll -> 2
문제 접근: haystack을 루프 돌면서 needle갯수만큼 문자열을 추출하여 equals 비교만 하면 간단히 할 수 있다. 반복문 조건만 array 범위 안넘어가게만 신경쓰면 된다.
구현코드:
class Solution {
public int strStr(String haystack, String needle) {
int answer = -1;
if (needle.length() > haystack.length()) return answer;
// 문자열 길이가 같으면 단순히 같은지만 판단하고 종료
if (haystack.length() == needle.length()) return haystack.equals(needle) ? 0 : -1;
// 루프 조건을 신경쓰자. (substring 함수에 array범위 안넘어가게 해야함)
for (int i = 0; i < haystack.length() && i + needle.length() <= haystack.length(); i++) {
String substr = haystack.substring(i, i + needle.length());
if (needle.equals(substr)) {
answer = i;
break;
}
}
return answer;
}
}
이 문제역시 싫어요가 많은데.. easy문제가 엄청많은데, 싫어요 많은 문제를 굳이 풀어야할까..?
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 278. First Bad Version (0) | 2021.01.11 |
---|---|
LeetCode 35. Search Insert Position (0) | 2021.01.11 |
LeetCode 26. Remove Duplicates from Sorted Array (0) | 2021.01.08 |
LeetCode 13. Roman to Integer (0) | 2021.01.07 |
LeetCode 337. House Robber III (0) | 2020.12.04 |