sean.jin
Spark Code Blog
sean.jin
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발공부
      • Kotlin
      • LeetCode
      • Algorithm
      • React
    • 주식차트
    • 책리뷰
    • 유틸리티

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 초보
  • 쿼드러플위칭데이
  • 책
  • 자기개발
  • 부의 추월차선
  • 네마녀의날
  • 주식책리뷰
  • 책추천
  • 책리뷰
  • 주식입문자
  • 변동성
  • 트리플 위칭데이
  • 오
  • 경제
  • 아빠와 딸의 주식투자 레슨
  • 주식투자

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
sean.jin

Spark Code Blog

[Kotlin] indexof 사용법 및 활용 LeetCode: Implement strStr() 쉬운풀이
개발공부/LeetCode

[Kotlin] indexof 사용법 및 활용 LeetCode: Implement strStr() 쉬운풀이

2021. 6. 26. 15:40
반응형
문제

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

 

일치하는게 없으면 -1, 일치하는게있으면 일치하는 문자의 첫번째자리를 리턴

만약 비어있는 string 이라면 0을 리턴한다.

예시

풀이

이번 예제에서는 indexof를 활용하여 풀어보겠습니다. 

class Solution {
     fun strStr(haystack: String, needle: String): Int {
        val hn = haystack.length // abcdddd
        val nn = needle.length // ddd
        if(hn==0 && nn==0){
            return 0
        }
        if(hn==0){
            return -1
        }
        if(nn==0){
            return 0
        } 
        
        //두 string의 길이가 0 이 아닌게 확인되면
        
        
        return haystack.indexOf(needle) //haystack에서 needle이 있는 위치에 첫자리를 리턴합니다.
        //만약 두개 일치하는게 없으면 -1을 리턴하게됩니다. 
    }
}
반응형

'개발공부 > LeetCode' 카테고리의 다른 글

[LeetCode] 190. Reverse Bits - JAVASCRIPT 풀이 과정 , 개념 설명 - 비트 연산자  (0) 2021.12.26
[Kotlin] 선형리스트를 활용한 문제풀이 LeetCode: Delete Node in a Linked List  (0) 2021.07.09
[Kotlin]String에 특수문자 제거, 띄어쓰기 제거(스페이스 제거), String 거꾸로 뒤집기, 소문자로변환 LeetCode :Valid PalindromeSolution  (0) 2021.06.24
[Kotlin] map, hashmap 같은지 비교하기 LeetCode: Valid Anagram  (0) 2021.06.22
[Kotlin] String에서 반복되지않은 char찾기 - LeetCode: First Unique Character in a String  (0) 2021.06.20
    '개발공부/LeetCode' 카테고리의 다른 글
    • [LeetCode] 190. Reverse Bits - JAVASCRIPT 풀이 과정 , 개념 설명 - 비트 연산자
    • [Kotlin] 선형리스트를 활용한 문제풀이 LeetCode: Delete Node in a Linked List
    • [Kotlin]String에 특수문자 제거, 띄어쓰기 제거(스페이스 제거), String 거꾸로 뒤집기, 소문자로변환 LeetCode :Valid PalindromeSolution
    • [Kotlin] map, hashmap 같은지 비교하기 LeetCode: Valid Anagram
    sean.jin
    sean.jin
    앱개발, 알고리즘, JS, Kotlin, 미국 취업준비

    티스토리툴바