标签:ret .com imp return put http rip output out
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; } };
标签:ret .com imp return put http rip output out
原文地址:http://www.cnblogs.com/SYSU-Bango/p/7967865.html