[关闭]
@w1024020103 2017-06-17T15:31:45.000000Z 字数 1313 阅读 469

Implement strStr()

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).

我的解法:

  1. class Solution {
  2. /**
  3. * Returns a index to the first occurrence of target in source,
  4. * or -1 if target is not part of source.
  5. * @param source string to be scanned.
  6. * @param target string containing the sequence of characters to match.
  7. */
  8. public int strStr(String source, String target) {
  9. // write your code here
  10. if (source == null || target == null){
  11. return -1;
  12. }
  13. int lenOfSource = source.length();
  14. int lenOfTarget = target.length();
  15. if (lenOfSource < lenOfTarget){
  16. return -1;
  17. } else if (lenOfSource == lenOfTarget){
  18. if (target.equals(source)){
  19. return 0;
  20. } else {
  21. return -1;
  22. }
  23. } else if (lenOfSource > lenOfTarget){
  24. for (int i = 0; i < lenOfSource - lenOfTarget + 1; i++){
  25. if (target.equals(source.substring(i, i + lenOfTarget))){
  26. return i;
  27. }
  28. }
  29. }
  30. return -1;
  31. }
  32. }

感觉我的思路很Straightforwawrd, 分为三种情况:
- source的长度比target还小,直接return -1;
- source的长度与target相等,如果包含子串,则与子串相等,返回0;
- source的长度比target大,则依次检查原串是否包含子串;

第三种情况里,注意:

  1. for (int i = 0; i < lenOfSource - lenOfTarget + 1; i++){
  2. if (target.equals(source.substring(i, i + lenOfTarget))){
  3. return i;
  4. }
  5. }

从原字符串的index = 0开始,依次循环到可能包含子串的Index为止。如果只剩下不到子串长度的字符串,则不需要再继续检查了。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注