LeetCode - The World's Leading Online Programming Learning Platform

Problem

  1. input: 문자열 haystack, 문자열 needle
  2. output: haystack에서 needle이 처음으로 등장하는 idx 리턴
  3. needle이 등장하지 않는 경우 -1 리턴

Idea

문자열의 길이가 짧기 때문에 왠만하면 통과된다.

indexOf() 의 기능과 동일하게 때문에 해당 메소드를 사용하여 통과 → Sol1

indexOf를 직접 구현하여 통과 → Sol2

Solution

  1. indexOf()

    class Solution {
        fun strStr(haystack: String, needle: String): Int {
            return haystack.indexOf(needle)
        }
    }
    

    Untitled

  2. 문자열의 순회하며 직접 비교

    indexOf() 구현

    class Solution {
        fun strStr(haystack: String, needle: String): Int {
            var idx = 0
            while (idx <= haystack.length - needle.length) {
                var cnt = 0
                for (i in needle.indices) {
                    if (haystack[idx + i] == needle[i]) cnt++
                    else break
                }
                if (cnt == needle.length) return idx
                else idx++
            }
            return -1
        }
    }
    

    Untitled

Point