首页 > 其他 > 详细

Implement strStr()_LeetCode

时间:2017-12-03 23:28:36      阅读:212      评论:0      收藏:0      [点我收藏+]

Description:

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

 

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

算法思想:
通过两重循环来遍历。
外层循环的长度为m-n。

代码:
class Solution {
public:
    int strStr(string haystack, string needle) {
         int m = haystack.length();
         int n = needle.length();
        if (n == 0) {
            return 0;
        }
        for (int i = 0; i < m - n + 1; i++) {
            int j = 0;
            for (; j < n; j++)
                if (haystack[i + j] != needle[j])
                    break;
            if (j == n) 
                return i;
        }
        return -1;
    }
};

 



Implement strStr()_LeetCode

原文:http://www.cnblogs.com/SYSU-Bango/p/7967865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!