’ Implement strStr()’ in LeetCode (Easy)
📌 Problem
https://leetcode.com/problems/implement-strstr/
📌 Answer
The Point
String methods :
contains()
,indexOf()
reference: https://www.w3schools.com/java/java_ref_string.asp
1
2
3
4
5
6
7
class Solution {
public int strStr(String haystack, String needle) {
if (needle == "" || haystack == "") return 0;
else if (haystack.contains(needle)) return haystack.indexOf(needle);
else return -1;
}
}
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}
}
Comments powered by Disqus.