• 문제 링크
Find the Index of the First Occurrence in a String - LeetCode
Can you solve this real interview question? Find the Index of the First Occurrence in a String - Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: I
leetcode.com
• 풀이 코드
public class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length() - needle.length() + 1, m = needle.length();
for (int i = 0; i < n; i++)
if (haystack.charAt(i) == needle.charAt(0) && compare(haystack, needle, m, i)) return i;
return -1;
}
private boolean compare(String a, String b, int m, int i) {
for (int j = 1; j < m; j++) if (a.charAt(i + j) != b.charAt(j)) return false;
return true;
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 35. Search Insert Position - Java (0) | 2026.05.18 |
|---|---|
| [LeetCode] 24. Swap Nodes in Pairs - Java (0) | 2026.05.17 |
| [LeetCode] 27. Remove Element - Java (0) | 2026.05.15 |
| [LeetCode] 26. Remove Duplicates from Sorted Array - Java (0) | 2026.05.14 |
| [LeetCode] 21. Merge Two Sorted Lists - Java (0) | 2026.05.13 |
댓글