Post

πŸ’‘ LeetCode 28 - Find the Index of the First Occurrence in a String

πŸ’‘ LeetCode 28 - 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.

μž…μΆœλ ₯ 예제

βœ… 예제 1

1
2
3
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.

βœ… 예제 2

1
2
3
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.​

μ œμ•½μ‘°κ±΄

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

μž‘μ„± μ½”λ“œ

1
2
3
4
5
6
class Solution {
	public int strStr(String haystack, String needle) {
		// λ°˜ν™˜
		return haystack.indexOf(needle);
	}
}

회고

  • ν•„μžλŠ” String.indexOf() λ©”μ„œλ“œλ₯Ό 잘 μ•ˆ μ“°λŠ”λ°, 졜근 Tistory 이웃 λ‹˜μ˜ ν¬μŠ€νŒ…μ—μ„œ ν•΄λ‹Ή λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ 문제 ν’€μ΄ν•œ μ½”λ“œλ₯Ό 보게 λΌμ„œ μ μš©ν•΄λ³΄μ•˜λ‹€.
  • 슀슀둜 μ½”λ“œ μ§œλŠ” 것도 μ€‘μš”ν•˜μ§€λ§Œ λ‹€λ₯Έ 뢄듀이 μ–΄λ–€ 아이디어λ₯Ό κ°–κ³  μ½”λ“œλ₯Ό μž‘μ„±ν•˜λŠ” 지도 μ‚΄νŽ΄λ³΄λŠ” 것이 곡뢀가 많이 λ˜λŠ” 것 κ°™λ‹€.Β Β 
This post is licensed under CC BY 4.0 by the author.