LeetCode 28. Implement strStr()

https://leetcode.com/problems/implement-strstr/

Implement strStr().

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

  • 字符串简单题。一定要写的没BUG。两种解法,一种用string::find函数,另一种比较字符串。
  • 如果不在函数最后一行写return语句的话,LeetCode会出RUNTIME ERROR。
Line 27: control reaches end of non-void function [-Werror=return-type]
  • strstr - C++ Reference
    •   http://www.cplusplus.com/reference/cstring/strstr/?kw=strstr 
  • 注意haystack.size() - needle.size() + 1需要显示转换为int,否则值为-1时unsigned long会自动转变
 1 //
 2 //  main.cpp
 3 //  LeetCode
 4 //
 5 //  Created by Hao on 2017/3/16.
 6 //  Copyright © 2017年 Hao. All rights reserved.
 7 //
 8 
 9 #include <iostream>
10 #include <cstring>
11 #include <vector>
12 #include <cmath>
13 using namespace std;
14 
15 class Solution {
16 public:
17     // with string::find function
18     int strStr(string haystack, string needle) {
19         return (haystack.find(needle) != string::npos) ? haystack.find(needle) : -1;
20     }
21     
22     // compare string
23     int strStr1(string haystack, string needle) {
24         // Corner case
25         if (needle.empty()) return 0; // for both empty string should return 0
26         if (haystack.empty()) return -1;
27         
28         bool flag;
29         int n = haystack.size() - needle.size() + 1; // pay attention to + 1
30         
31         // better use < instead of <=
32         for (int i = 0; i < n; i ++) {
33             flag = true;
34             
35             for (int j = 0; j < needle.size(); j ++)
36                 if (haystack.at(i + j) != needle.at(j)) {
37                     flag = false;
38                     break;
39                 }
40             
41             if (flag)
42                 return i;
43         }
44         
45         return -1;
46     }
47 };
48 
49 int main(int argc, char* argv[])
50 {
51     Solution    testSolution;
52     string      result;
53     
54     vector<vector<string>> sVec = {{"aaa","aaaa"}, {"", ""}, {"aaaaa", "bba"}, {"hello", "ll"}};
55     
56     /*
57      -1
58      -1
59      0
60      0
61      -1
62      -1
63      2
64      2
65      */
66     for (auto s : sVec) {
67         cout << testSolution.strStr(s[0], s[1]) << endl;
68         cout << testSolution.strStr1(s[0], s[1]) << endl;
69     }
70 
71     return 0;
72 }
View Code

 

 
posted on 2016-06-24 23:12  浩然119  阅读(360)  评论(0编辑  收藏  举报