@w1024020103
2017-06-17T15:31:45.000000Z
字数 1313
阅读 469
LeetCode
注意substring()的用法:
public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
startIndex: inclusive
endIndex: exclusive
eg:
String s="hello";
System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
我的解法:
class Solution {
/**
* Returns a index to the first occurrence of target in source,
* or -1 if target is not part of source.
* @param source string to be scanned.
* @param target string containing the sequence of characters to match.
*/
public int strStr(String source, String target) {
// write your code here
if (source == null || target == null){
return -1;
}
int lenOfSource = source.length();
int lenOfTarget = target.length();
if (lenOfSource < lenOfTarget){
return -1;
} else if (lenOfSource == lenOfTarget){
if (target.equals(source)){
return 0;
} else {
return -1;
}
} else if (lenOfSource > lenOfTarget){
for (int i = 0; i < lenOfSource - lenOfTarget + 1; i++){
if (target.equals(source.substring(i, i + lenOfTarget))){
return i;
}
}
}
return -1;
}
}
感觉我的思路很Straightforwawrd, 分为三种情况:
- source的长度比target还小,直接return -1;
- source的长度与target相等,如果包含子串,则与子串相等,返回0;
- source的长度比target大,则依次检查原串是否包含子串;
第三种情况里,注意:
for (int i = 0; i < lenOfSource - lenOfTarget + 1; i++){
if (target.equals(source.substring(i, i + lenOfTarget))){
return i;
}
}
从原字符串的index = 0开始,依次循环到可能包含子串的Index为止。如果只剩下不到子串长度的字符串,则不需要再继续检查了。