PS/LeetCode
[LeetCode] May Challenge 2 - Jewels and Stones
판교토끼
2020. 5. 3. 11:30
728x90
https://leetcode.com/problems/jewels-and-stones/
Jewels and Stones - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
2일차 May Challenge 문제였는데, S에 속한 문자 중 J에 속한 것이 몇 개인지 구하는 문제였다. 단순한 선형 탐색을 통해 구현하였다. 다른 풀이로 string의 contains 메소드를 사용하였는데, 시간 차이는 4ms로 많이 나지 않았다. 아마 Contains 메소드가 O(nk)로 선형 탐색과 차이나지 않기 때문인 것 같다.
public class Solution {
public int NumJewelsInStones(string J, string S) {
int result=0;
for(int i=0;i<S.Length;i++) {
char temp=S[i];
for(int j=0;j<J.Length;j++) {
if(temp==J[j]) {
result++;
break;
}
}
}
return result;
}
}
public class Solution {
public int NumJewelsInStones(string J, string S) {
int result=0;
for(int i=0;i<S.Length;i++) {
char temp=S[i];
if(J.Contains(temp))
result++;
}
return result;
}
}
728x90