Easy-题目57:28. Implement strStr()
来源:互联网 发布:逆希尔伯特矩阵 编辑:程序博客网 时间:2024/05/11 22:02
题目原文:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目大意:
实现strStr()函数。返回needle字符串在haystack字符串中首次出现的下标,如果needle不是haystack的子串则返回-1.
题目分析:
c99中strstr函数的接口不对,因此使用Java中的indexOf()方法水过。
源码:(language:java)
public class Solution { public int strStr(String haystack, String needle) { return haystack.indexOf(needle); }}
成绩:
1ms,beats 69.31%,众数1ms,29.29%.
cmershen的碎碎念:
附C99中strstr()函数源码:
char *strstr(constchar*s1,constchar*s2){ int n; if(*s2) { while(*s1) { for(n=0;*(s1+n)==*(s2+n);n++) { if(!*(s2+n+1)) return(char*)s1; } s1++; } return NULL; } else return (char*)s1;}
但是稍加改动(简单改动了一下return的部分)之后放入OJ居然会提示TLE!也许C99的源码存在问题有待思考。
再附jdk中indexOf的底层实现供研究:
static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { if (fromIndex >= sourceCount) { return (targetCount == 0 ? sourceCount : -1); } if (fromIndex < 0) { fromIndex = 0; } if (targetCount == 0) { return fromIndex; } char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); for (int i = sourceOffset + fromIndex; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* Found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i - sourceOffset; } } } return -1;}
对了 这东西叫 kmp算法吧??
0 0
- Easy-题目57:28. Implement strStr()
- 28. Implement strStr() [easy]
- 【Easy】28. Implement strStr()
- 28. Implement strStr() [easy] (Python)
- Leetcode 28. Implement strStr() (Easy) (cpp)
- Leetcode[easy] - Implement strStr()
- LeetCode-Easy-Java-Implement strStr()
- Leet Code OJ 28. Implement strStr() [Difficulty: Easy]
- [LeetCode] 028. Implement strStr() (Easy) (C++/Python)
- LeetCode-28-Implement strStr()(Sting/穷举)-Easy
- Easy 9 Implement strStr()(28)
- LeetCode OJ 28 Implement strStr() [Easy]
- (算法分析Week6)Implement strStr()[Easy]
- LeetCode-Easy刷题(9) Implement strStr()
- [LeetCode]28.Implement strStr()
- LeetCode --- 28. Implement strStr()
- LeetCode 28.Implement strStr()
- [Leetcode] 28. Implement strStr()
- 解读OpenGL棋盘纹理贴图
- 干掉蓝光播放器,KODI称王
- request.getParameter() 和request.getAttribute() 区别
- shell下时间日期的加减乘除运算
- Python学习之基础总结--2
- Easy-题目57:28. Implement strStr()
- jq过滤器方法 选择器
- UML之用例图
- 析构函数和对象数组和对象指针
- 快速理解android事件传递拦截机制概念
- bash 遍历目录下文件
- wired unmanage ubuntu14.04
- 【Java】LRS最小重复子串
- 解决android使用gson解析json字符串,并使用混淆编译方式打包apk遇到的问题