π‘ 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.