• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Implement strStr()

可以用c的方法

 1 class Solution {
 2 public:
 3     char *strStr(char *haystack, char *needle) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         int haylen = strlen(haystack);
 7         int needlen = strlen(needle);
 8         for (int i = 0; i <= haylen-needlen; i++) {
 9             char *p = haystack + i;
10             char *q = needle;
11             while (*q != '\0' && *p == *q) {
12                 p++, q++;
13             }
14             if (*q == '\0') return haystack + i;
15         }
16         return NULL;
17     }
18 };

 

再贴段更加清晰的代码

 1 class Solution {
 2 public:
 3     char *strStr(char *haystack, char *needle) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         string S, T;
 7         for (int i = 0; *(haystack+i) != '\0'; i++) S += *(haystack+i);
 8         for (int i = 0; *(needle+i) != '\0'; i++) T += *(needle+i);
 9         int m = S.size();
10         int n = T.size();
11         if (!n) return haystack;
12         for (int i = 0; i < m-n+1; i++) {
13             if (S.substr(i, n) == T) return haystack+i;
14         }
15         return NULL;
16     }
17 };

 

1 public class Solution {
2     public int StrStr(string haystack, string needle) {
3         if (needle.Length == 0) return 0;
4         for (int i = 0; i < haystack.Length - needle.Length + 1; i++) {
5             if (haystack.Substring(i, needle.Length) == needle) return i;
6         }
7         return -1;
8     }
9 }
View Code

 

posted @ 2013-03-21 15:32  ying_vincent  阅读(140)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3