[Programmers] #120908 - 문자열안에 문자열 [Java][C++][Python]
[Programmers] #120908 - 문자열안에 문자열 [Java][C++][Python]
1. 아이디어
문자열 str1안에 문자열 str2가 존재하는지 판단하면 되는 문제다. 언어별 내장 함수를 활용하면 간단하게 해결할 수 있다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N \times M)$ | $O(1)$ |
($N$ = str1의 길이, $M$ = str2의 길이. Python의 in은 CPython 구현상 $O(N + M)$)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
class Solution {
public int solution(String str1, String str2) {
return str1.contains(str2) ? 1 : 2;
}
}
1
2
3
4
5
6
#include <bits/stdc++.h>
using namespace std;
int solution(string str1, string str2) {
return str1.find(str2) != -1 ? 1 : 2;
}
find는 str2가 str1에서 처음 나타나는 위치의 인덱스를, 없으면 std::string::npos를 반환한다. std::string::npos는 size_t 최댓값이라 -1을 size_t로 변환한 것과 같아 해당 방식으로 검사할 수 있다.
1
2
def solution(str1, str2):
return 1 if str2 in str1 else 2
This post is licensed under CC BY 4.0 by the author.