
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从 0 开始)。如果不存在,则返回 -1 。
在面试中我是否需要实现 KMP 算法?
输入: source = "source" ,target = "target" 输出:-1 样例解释: 如果 source 里没有包含 target 的内容,返回-1 输入: source = "abcdabcdefg" ,target = "bcd" 输出: 1 样例解释: 如果 source 里包含 target 的内容,返回 target 在 source 里第一次出现的位置 算法:模拟
因为本题的时间复杂度比较宽限,不需要更为复杂的 KMP 算法,可以直接模拟,逐一比对每个字符。
M 表示 source 的长度 N 表示 target 的长度 空间复杂度:O(M+N) 时间复杂度:O(MN)
public class Solution { /** * @param source: * @param target: * @return: return the index */ public int strStr(String source, String target) { //获取两个字符串的长度 int sourceLen = source.length(); int targetLen = target.length(); //注意特判,若 target 长度为 0 则答案为 0 if(targetLen == 0){ return 0; } //若 target 长度大于 source,则不可能匹配 if(targetLen > sourceLen){ return -1; } for(int i = 0; i < sourceLen-targetLen+1; i++){ //k 表示比对时 source 中所指向的字符 int k = i; for(int j = 0; j < targetLen; j++){ if(source.charAt(k) == target.charAt(j)){ //最后一个字符匹配完成,输出答案 if(j == targetLen - 1){ return i; } k++; } //其中一个字符无法匹配,直接退出做下一次循环 else{ break; } } } return -1; } }