Implement strStr()
2015-08-31 20:28
351 查看
Description:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Code1:
Code2:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Code1:
vector<int> getNext ( string&t ) { size_t n = t.length(); vector<int>next(n,-1); int i = 0, j = -1; while ( i < n-1 ) { if ( j == -1 || t[i] == t[j]) { ++i; ++j; next[i] = j; } else j = next[j]; }return next; } int indexKMP( string& t, string&w, vector<int>& next ) { int i = 0, j = 0; int lengthT = t.length(); int lengthW = w.length(); while ( i < lengthT && j < lengthW ) { if ( j == -1 || t[i] == w[j] ) //继续比较后继字符 { ++i; ++j; } else j = next[j]; } if ( j == lengthW ) return i - lengthW; else return -1; } int strStr(string haystack, string needle) { if (needle == "") return 0; if (haystack == "") return -1; vector<int>next; next = getNext(needle); return indexKMP(haystack,needle,next); return -1; }
Code2:
int strStr(string a, string b) {//a为目标串,b为字串 if (b == "") return 0; if (b.size() > a.size() ) return -1; for (int i = 0; i <= a.size()-b.size(); ++i) { int j = 0; for (; j < b.size(); ++j) { if (a[i+j]!=b[j]) break; } if (j==b.size()) return i; } return -1; }
相关文章推荐
- 关于Android中的输入法
- bzoj 2049
- linux程序包管理
- 小打小闹已经开始
- 惠普记事(一)
- IOS 开发笔记——做日历开发的总结
- 共有113款 手机Web开发框架开源软件
- 如何成为一名卓越的前端工程师
- DirectX API 编程起步 #02 窗口的诞生
- bzoj 2049
- HUST1341A Simple Task【模拟】
- 九的余数
- 点击键盘收回的事件
- 机器学习中的两个概率模型
- Android Drawable系列(1):自定义背景以及注意事项
- POJ Oulipo (KMP)
- 15年8月英语小结-新的开始
- C语言--字符串
- 剑指offer-第六章面试中的各项能力之总结
- ubuntu windows 双系统 修改启动项名称