首页 > 代码库 > strStr
strStr
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。