LeetCode题解:Implement strStr()
2015-08-21 15:16
411 查看
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:求needle代表的字符串在haystack字符串中第一次出现的位置
解决思路:
传统字符串匹配算法
KMP
代码:
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:求needle代表的字符串在haystack字符串中第一次出现的位置
解决思路:
传统字符串匹配算法
KMP
代码:
public class Solution { private int[] getNext(char[] str){ int[] next = new int[str.length]; for(int i = 1;i < next.length;++i){ int j = next[i]; while(j > 0 && str[j] != str[i]){ if(j == 1 && next[j] == 1){ j = 0; }else{ j = next[j]; } } if(j > 0 || str[j] == str[i]){ next[i] = j + 1; } } return next; } public int strStr(String haystack, String needle) { if(needle.length() == 0){ return 0; } if(needle.length() <= haystack.length()){ int[] next = getNext(needle.toCharArray()); int i = 0; int j = 0; while(i < haystack.length()){ if(haystack.charAt(i) == needle.charAt(j)){ ++i; ++j; if(j == needle.length()){ return i - j; } }else if(j > 0){ j = next[j]; }else{ ++i; } } } return -1; } }
相关文章推荐
- 在线语音听写
- 关于命名空间
- phpcms v9 企业黄页加入企业会员提示“请选择企业库类型!”
- 【完全开源】百度地图Web service API C#.NET版,带地图显示控件、导航控件、POI查找控件
- HeadFirst 设计模式 12复合模式
- angularJs 菜单的timeout和delay处理
- js 全选
- iOS 制作圆形头像
- poj-1442 Black Box
- Foreach用法
- 程序员的生活充满压力,但你不能放弃!
- intellj(idea) 编译项目时在warnings 页签框里 报 “xxx包不存在” 或 “找不到符号” 或 “未结束的字符串字面值” 或 “需要)” 或 “需要;”等错误提示
- hdu 5299 树上博弈
- android中判断是否为空遇到的问题
- hdu5407
- 系统架构 很喜欢所以转发了
- 访问控制(public .private .protected )
- 二叉查找各类情况总结
- Android zygote分析——学习笔记
- U-boot-2014.04移植到MINI2440(1) 初步探索移植