码迷,mamicode.com
首页 > 其他好文 > 详细

(leetcode) Implement strStr()

时间:2015-06-01 18:26:18      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

(1)传统的字符串匹配算法:

注意这道题中各种特殊情况的返回值。

传统字符串匹配就是让目标字符串从第一个字母开始逐个匹配源字符串的每一个字符,直到匹配完全。

class Solution {
public:
    int strStr(string haystack, string needle) {
        int i,j;
		i = 0;
		j = 0;
        if(needle.empty()) return 0;

        if(haystack.length() < needle.length())
		{
			return -1;
		}
		int lenh,lenn;
		lenh = haystack.length();
		lenn = needle.length();

		while(i !=lenh && j!=lenn)
		{
			if(haystack[i] == needle[j])
			{
				++i;
				++j;
			}
			else
			{
				i = i - j +1;
				j = 0;
			}
		}

		return j == lenn ? i - j : -1;
    }
};

  (2) 使用KMP算法

 

(leetcode) Implement strStr()

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4544183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!