넘치게 채우기

[LeetCode] 28. Find the Index of the First Occurrence in a String 본문

PS/LeetCode

[LeetCode] 28. Find the Index of the First Occurrence in a String

riveroverflow 2023. 8. 6. 13:50
728x90
반응형

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/?envType=study-plan-v2&envId=top-interview-150 

 

Find the Index of the First Occurrence in a String - LeetCode

Can you solve this real interview question? 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.   Example 1: I

leetcode.com

문제 유형 : 문자열 처리

문제 난이도 : Easy

 

문제

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.

 

haystack 과 needle이라는 두 문자열이 주어진다. haystack에서 처음으로 나오는 needle의 인덱스를 찾아 반환하고, 없으면 -1을 반환하라.

 

풀이

find함수를 이용하면 쉽게 찾을 수 있다.

 

코드

C++

class Solution {
public:
    int strStr(string haystack, string needle) {
        ios_base::sync_with_stdio(false);
        cin.tie(nullptr);

        size_t pos = haystack.find(needle);

        if (pos == string::npos) {
            return -1;
        }

        return pos;
    }
};

Dart

class Solution {
  int strStr(String haystack, String needle) {
    int pos = haystack.indexOf(needle);
    return pos != -1? pos : -1;
  }
}

Java

class Solution {
    public int strStr(String haystack, String needle) {
        int idx = haystack.indexOf(needle);

        return idx != -1? idx:-1;
    }
}

Python3

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        try:
            return haystack.index(needle)
        except ValueError:
            return -1

swift

class Solution {
    func strStr(_ haystack: String, _ needle: String) -> Int {
        if let range = haystack.range(of: needle) {
            return haystack.distance(from: haystack.startIndex, to: range.lowerBound)
        } else {
            return -1
        }
    }
}
 
728x90
반응형

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] 33. Search in Rotated Sorted Array  (0) 2023.08.08
[LeetCode] 68. Text Justification  (0) 2023.08.07
[LeetCode] 6. Zigzag Conversion  (0) 2023.08.05
[LeetCode] 139. Word Break  (0) 2023.08.04
[LeetCode] 151. Reverse Words in a String  (0) 2023.08.03