首页 > 其他 > 详细

strStr

时间:2016-07-06 09:53:35      阅读:219      评论:0      收藏:0      [点我收藏+]

For a given source string and a target string, you should output the first index(from 0) of target string in source string.

If target does not exist in source, just return -1.

Example

If source = "source" and target = "target", return -1.

If source = "abcdabcdefg" and target = "bcd", return 1.

 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         if (source == null || target == null)
10         return -1;
11         
12         if (target.length() == 0) return 0;
13         
14         if (source.length() < target.length()) return -1;
15         
16         for (int i = 0; i < source.length(); i++) {
17             boolean isAllChecked = true;
18             for (int j = 0; j < target.length(); j++) {
19                 if (i + j >= source.length() || target.charAt(j) != source.charAt(i + j)) {
20                     isAllChecked = false;
21                     break;
22                 }
23             }
24             
25             if (isAllChecked == true) {
26                 return i;
27             }
28         }
29         return -1;
30     }
31 }

 

strStr

原文:http://www.cnblogs.com/beiyeqingteng/p/5645652.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!