您的位置:首页 > 编程语言 > Java开发

朴素模式匹配算法java实现

2016-03-25 16:31 423 查看

对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。

class Solution {
/**
* Returns a index to the first occurrence of target in source,
* or -1  if target is not part of source.
* @param source string to be scanned.
* @param target string containing the sequence of characters to match.
*/
public int strStr(String source, String target) {
//write your code here
//注意传入null参数的情况
if(null == source || null == target ){
return -1;
}
int lenS = source.length();
int lenT = target.length();
for (int s = 0; s <= lenS - lenT; s++) {
boolean sEqual = true;
int i = 0;
while(sEqual && i < lenT){
if(source.charAt(s + i) == target.charAt(i)){
i++;
}else{
sEqual = false;
}
}
if(sEqual){
return s;
}
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法