码迷,mamicode.com
首页 > 其他好文 > 详细

strStr

时间:2016-07-06 09:54:02      阅读:123      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!