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

strStr

时间:2017-05-10 14:32:25      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:targe   pre   exist   first   tput   sequence   ==   bsp   注意   

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

看别人的博客 偶尔提到播放器算法 顺便写一写 复习一下

两个注意的地方

   一是输入检查 target 为空的情况 直接返回0;

   二是返回值计算的时候 是sIndex-tIndex 而不是 sIndex-tIndex+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     int[] p;
 9     public int strStr(String source, String target) {
10         // write your code here
11         if(source==null||target==null||target.length()>source.length()) return -1;
12         if(target.length()==0) return 0;
13         preProcess(target);
14         int sIndex =0, tIndex = 0;
15         
16         while(sIndex<source.length()){
17             if(source.charAt(sIndex)==target.charAt(tIndex)){
18                 sIndex++;
19                 tIndex++;
20             }else{
21                 if(tIndex>0){
22                     tIndex = p[tIndex];
23                 }else{
24                     sIndex++;
25                 }
26             }
27             if(tIndex==target.length()) return sIndex-tIndex;
28         }
29         return -1;
30         
31     }
32     private void preProcess(String target){
33         p = new int[target.length()];
34         int i=1;
35         while(i<target.length()){
36             int j = p[i-1];
37             while(j>0&&target.charAt(j)!=target.charAt(i)) j = p[j-1];
38             if(target.charAt(j)==target.charAt(i)){
39                 p[i] = j+1;
40             }
41             i++;
42         }
43     }
44 }

 

strStr

标签:targe   pre   exist   first   tput   sequence   ==   bsp   注意   

原文地址:http://www.cnblogs.com/xinqiwm2010/p/6835397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!