Home [Java String methods] Implement strStr()
Post
Cancel

[Java String methods] Implement strStr()

’ Implement strStr()’ in LeetCode (Easy)


📌 Problem

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

📌 Answer

The Point

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;
            }
        }
    }
}
This post is licensed under CC BY 4.0 by the author.

[Easy] Remove Duplicates from Sorted Array

[Easy] Plus One

Comments powered by Disqus.