题目描述
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。
如果不存在,则返回 -1。
样例1
输入: source = "source" , target = "target"
输出:-1
样例解释: 如果source里没有包含target的内容,返回-1
样例2
输入: source = "abcdabcdefg" ,target = "bcd"
输出: 1
样例解释: 如果source里包含target的内容,返回target在source里第一次出现的位置
java题解
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) {
if (source == null || target == null) {
return -1;
}
for (int i = 0; i < source.length() - target.length() + 1; i++) {
int j = 0;
for (j = 0; j < target.length(); j++) {
if (source.charAt(i + j) != target.charAt(j)) {
break;
}
}
// finished loop, target found
if (j == target.length()) {
return i;
}
}
return -1;
}
}
C++题解
class Solution {
public:
int strStr(string source, string target) {
int i, j, lenh = source.length(), lenn = target.length();
if (lenn == 0) return 0;
for (i = 0; i <= lenh - lenn; i++) {
for (j = 0; j < lenn; j++)
if (source[i + j] != target[j]) break;
// 匹配成功
if (j == lenn) return i;
}
return -1;
}
};
python题解
class Solution:
def strStr(self, source, target):
if source is None or target is None:
return -1
len_s = len(source)
len_t = len(target)
for i in range(len_s - len_t + 1):
j = 0
while (j < len_t):
if source[i + j] != target[j]:
break
j += 1
if j == len_t:
return i
return -1