File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -137,6 +137,7 @@ My accepted leetcode solutions to some of the common interview problems.
137137- [ String to Integer] ( problems/src/string/StringToInteger.java ) (Medium)
138138- [ Text Justification] ( problems/src/string/TextJustification.java ) (Hard)
139139- [ ZigZag Conversion] ( problems/src/string/ZigZagConversion.java ) (Medium)
140+ - [ Implement StrStr] ( problems/src/string/ImplementStrStr.java ) (Easy)
140141
141142
142143#### [ Tree] ( problems/src/tree )
Original file line number Diff line number Diff line change 1+ package string ;
2+
3+ /**
4+ * Created by gouthamvidyapradhan on 24/06/2017.
5+ * Implement strStr().
6+
7+ Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
8+
9+ Solution O(N ^ 2)
10+ */
11+ public class ImplementStrStr {
12+ public static void main (String [] args ) throws Exception {
13+ System .out .println (new ImplementStrStr ().strStr ("AABB" , "" ));
14+ }
15+
16+ public int strStr (String haystack , String needle ) {
17+ if (haystack .isEmpty () && needle .isEmpty ()) return 0 ;
18+ if (needle .isEmpty ()) return 0 ;
19+ for (int i = 0 , l = haystack .length (); i < l ; i ++){
20+ if (haystack .charAt (i ) == needle .charAt (0 )){
21+ if (isEqual (haystack , needle , i ))
22+ return i ;
23+ }
24+ }
25+ return -1 ;
26+ }
27+
28+ private boolean isEqual (String haystack , String needle , int i ){
29+ int hL = haystack .length ();
30+ int nL = needle .length ();
31+ int j = 0 ;
32+ while (i < hL && j < nL ){
33+ if (haystack .charAt (i ) != needle .charAt (j ))
34+ return false ;
35+ i ++;
36+ j ++;
37+ }
38+ return j >= nL ;
39+ }
40+
41+
42+ }
You can’t perform that action at this time.
0 commit comments