Easy-题目57:28. Implement strStr()
2016-05-30 20:56
267 查看
题目原文:
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)
成绩:
1ms,beats 69.31%,众数1ms,29.29%.
cmershen的碎碎念:
附C99中strstr()函数源码:
但是稍加改动(简单改动了一下return的部分)之后放入OJ居然会提示TLE!也许C99的源码存在问题有待思考。
再附jdk中indexOf的底层实现供研究:
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算法吧??
相关文章推荐
- request.getParameter() 和request.getAttribute() 区别
- appserv - 最简单的绑定路径
- 用malloc动态申请一个二维数组的三种方法
- 正则大全
- 51nod 棋盘问题(博弈论)
- shell下时间日期的加减乘除运算
- 手动为ubuntu虚拟机配置Ip地址
- 【Java学习笔记】进制转换
- 异常
- Python学习之基础总结--1
- 《深入浅出Node.js》学习笔记——(四)异步编程
- Easy-题目56:303. Range Sum Query – Immutable
- OpenCV学习Laplacian 变换及其运用
- 接口
- hdu-2035-人见人爱A^B-数的快速幂
- 本周任务
- JAVA之旅(十)——异常的概述,Try-Catch,异常声明Throws,多异常处理,自定义异常,Throw和Throws的区别
- JAVA之旅(十)——异常的概述,Try-Catch,异常声明Throws,多异常处理,自定义异常,Throw和Throws的区别
- [bzoj2818]gcd
- hrbust 2155 钱多多【水题】