LeetCode - 28. Implement strStr()(Two Pointers, String, String Matching)*

YAMAMAMO·2022년 2월 9일
0

LeetCode

목록 보기
21/100

문제

strStr()을 구현합니다.
건초 더미에서 바늘이 처음 나타나는 인덱스를 반환하고, 바늘이 건초 더미의 일부가 아닌 경우 -1을 반환합니다.
설명:
바늘이 빈 끈일 때 우리는 무엇을 반환해야 하나요? 이것은 면접을 볼 때 좋은 질문입니다.
이 문제를 해결하기 위해 바늘이 빈 문자열일 때 0을 반환하겠습니다. 이는 C의 strstr() 및 Java의 IndexOf()와 일치한다.

https://leetcode.com/problems/implement-strstr/

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().

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Example 3:

Input: haystack = "", needle = ""
Output: 0

풀이

자바입니다.

  • substring() 을 사용합니다.
    substring(start,end), start 부터 end 전 까지 출력합니다.
    ex) String a = "hello";
    a.substring(2,4); //ll
    a.substring(0,3); //hel
    a.substring(1); //ello 시작점부터 마지막 까지 출력한다.
class Solution {
    public int strStr(String haystack, String needle) { 
        if(haystack.length()==0&&needle.length()==0) return 0;
        if(haystack.equals(needle)) return 0;
        int i = 0;
        for(int j=needle.length();j<=haystack.length();j++){
            if(needle.equals(haystack.substring(i,j))) return i;
            else i++;
        }
        return -1;
    }
}

처음에 2중 for문을 통하여 풀었지만 Time Limit Exceeded 에 막혀서 substring을 사용해서 풀었습니다. 또한 return haystack.indexOf(needle); 한 줄로 풀이가 가능합니다.

profile
안드로이드 개발자

0개의 댓글