Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- dynamic programming
- Math
- 파이썬
- array
- geometry
- 코딩테스트
- Method
- two pointers
- 코테
- java
- greedy
- string
- SQL
- Stack
- sorting
- Number Theory
- Data Structure
- Counting
- Tree
- Binary Search
- Class
- Binary Tree
- bit manipulation
- implement
- 구현
- simulation
- database
- Matrix
- hash table
- 자바
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Medium] 28. Find the Index of the First Occurrence in a String 본문
코딩테스트 풀이/JAVA
[LeetCode/Medium] 28. Find the Index of the First Occurrence in a String
무지맘 2022. 12. 26. 13:171. Input
1) 문자열 needle
2) 문자열 haystack
2. Output
1) haystack에서 needle이 처음 나타나는 인덱스를 반환
2) needle이 haystack에 없다면 –1을 반환
3. Constraint
1) 1 <= haystack.length, needle.length <= 10^4
2) haystack과 needle은 영어 소문자로만 구성되어 있다.
4. Example
Input: haystack = "sadbutsad", needle = "sad" -> Output: 0
설명: sad는 0번째와 6번째에서 나타나지만, 처음 나타난 것은 0번째이므로 0을 반환한다.
5. Code
1) 첫 코드(2022/07/15)
int n = needle.length();
if(n == 0)
return 0;
int h = haystack.length();
if(h < n)
return -1;
if(h == n){
if(haystack.equals(needle))
return 0;
else
return -1;
}
int output = -1;
for(int i=0 ; i<h ; i++){
if(haystack.charAt(i)==needle.charAt(0)){
if(i+n<=h && haystack.substring(i,i+n).equals(needle)){
output = i; break;
}
}
}
return output;
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[LeetCode/Easy] 1502. Can Make Arithmetic Progression From Sequence (0) | 2022.12.27 |
---|---|
[LeetCode/Easy] 551. Student Attendance Record I (0) | 2022.12.26 |
[LeetCode/Medium] 215. Kth Largest Element in an Array (0) | 2022.12.26 |
[LeetCode/Easy] 1491. Average Salary Excluding the Minimum and Maximum Salary (0) | 2022.12.26 |
[LeetCode/Easy] 1486. XOR Operation in an Array (0) | 2022.12.26 |