Find First Subsequence

Find First Subsequence

题目描述:

给定一个源字符串和目标字符串,找到源字符串中第一次出现目标字符串出现的位置。

例子:

具体描述见LeetCode28

解题思路:

主要的想法在于我们在遍历字符串的过程中如何判断当前位置是否出现目标字符串。这边用的是substr函数将字符串中的和目标字符串相同长度的子串剪切用于判断是否相同即可。另外需要注意的是边界条件的判断。空串以及字符串长度的判断。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack == needle) return 0;
if (haystack == "") return -1;
if (haystack.size() < needle.size()) return -1;
//以上三种情况直接返回即可
for (int i = 0; i <= haystack.size() - needle.size(); i++){
if (haystack.substr(i, needle.size()) == needle)
//遍历过程中对每个位置目标子串长度进行判断
return i;
}
return -1;
}
};