Skip to content

Commit f6b125b

Browse files
ImplementStrStr : Accepted
1 parent 58af5d3 commit f6b125b

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)