Implement strStr() 实现strStr函数 @ LeetCode
来源:互联网 发布:什么是大数据交易平台 编辑:程序博客网 时间:2024/05/28 03:01
题目:
实现strStr() 函数
经典题目!练习必做到bug free题
思路:
1.用indexOf找到第一次出现的index,如果找到则调用substring,否则返回null ==> 因为用到了indexOf,所以面试时候肯定不可以
2.用O(n2)的暴力匹配(推荐)
3 KMP O(n), 面试时一般不会要求写出
/** * Implement strStr(). * * Returns a pointer to the first occurrence of needle in haystack, or null if * needle is not part of haystack. * */public class S28 {public static void main(String[] args) {String haystack = "testing test";String needle = "test";System.out.println(strStr(haystack, needle));}public static String strStr(String haystack, String needle) {// 找到出现第一次的index int idx = haystack.indexOf(needle); if(idx < 0){// 没找到 return null; }else{// 利用index得到substring return haystack.substring(idx); } }}
值得注意的几点:
1 输入检测
2 越界检测
public class Solution { public String strStr(String haystack, String needle) { if(haystack==null || needle==null || needle.length()>haystack.length()){ return null; } int i=0, j=0; for(i=0; i<=haystack.length()-needle.length(); i++){ // Notice <= here! for(j=0; j<needle.length(); j++){ if(haystack.charAt(i+j) != needle.charAt(j)){ break; } } if(j == needle.length()){ return haystack.substring(i); } } return null; }}
- Implement strStr() 实现strStr函数 @ LeetCode
- leetcode 28. Implement strStr() 实现strStr()函数
- [C++]LeetCode 28: Implement strStr() (实现strStr()函数)
- LeetCode 28 Implement strStr()(实现strStr()函数)
- 【LeetCode】005 Implement strStr() 函数strStr()的功能实现
- leetcode | Implement strStr() | 实现字符串查找函数
- 【LeetCode-面试算法经典-Java实现】【028-Implement strStr() (实现strStr()函数)】
- Implement strStr() strncmp实现strstr()
- Leetcode刷题记——28. Implement strStr(实现strStr)
- LeetCode: Implement strStr()
- [Leetcode] Implement strstr()
- Leetcode: Implement strStr
- [Leetcode] Implement strStr()
- LeetCode Implement strStr()
- 【leetcode】Implement strStr()
- [LeetCode]Implement strStr()
- [LeetCode] Implement strStr()
- [LeetCode] Implement strStr()
- 高性能MySql进化论(五):提速Alter Table
- iOS error: No visible @interface for 'xxxx' declares the selector 'alloc'
- 计算机1-4班第01次作业思维总结
- 让C语言更高效
- 全排列 数据结构(机工出版) 递归算法 有改动 还有不完善的地方!
- Implement strStr() 实现strStr函数 @ LeetCode
- autohotkey +vba 利用文本文件传递数据
- 运维几个点
- java各种编码的解疑
- 1057. Stack
- tomcate
- 网络小测试
- eclipse利用jpcap getDeviceList 返回结果为null
- 20-activity第二步点击按钮,向第二个页面传递值