Skip to content

Commit e859fbc

Browse files
committed
strstr java code
1 parent 3e853a4 commit e859fbc

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ Gemfile.lock
88
node_modules
99
package.json
1010
images/Thumbs.db
11-
*.exe
11+
*.exe
12+
*.class

source_code/StrStr.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* @Author: Beinan
3+
* @Date: 2015-01-08 18:04:08
4+
* @Last Modified by: Beinan
5+
* @Last Modified time: 2015-01-08 18:27:53
6+
*/
7+
8+
public class StrStr {
9+
10+
/**
11+
* @param source the string being searched.
12+
* @param target the substring to search for
13+
* @return the index of the first occurrence of the specified substring,
14+
* starting at the specified index,
15+
* or {@code -1} if there is no such occurrence.
16+
*/
17+
public static int strStr(String source, String target){
18+
int max = source.length() - target.length();
19+
for(int i = 0; i <= max; i++){
20+
int matched_count = 0;
21+
for(/*nothing*/;
22+
matched_count < target.length()
23+
&& source.charAt(i + matched_count) == target.charAt(matched_count);
24+
matched_count++);
25+
if(matched_count == target.length())
26+
return i; //matched
27+
28+
}
29+
return -1;
30+
}
31+
32+
//test script
33+
public static void main(String[] args) {
34+
System.out.println(strStr("abcde", "cde"));
35+
System.out.println(strStr("abcde", "cdef"));
36+
}
37+
38+
39+
}

0 commit comments

Comments
 (0)