Java [leetcode 28]Implement strStr()
2024-10-15 11:11:33
题目描述:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
解题思路:
从开头开始,逐个匹配。
注意特殊情况。
代码如下:
public class Solution {
public static int strStr(String haystack, String needle) {
int haystackLength = haystack.length();
int needleLength = needle.length();
int j = 1;
if (needleLength == 0)
return 0;
if (needleLength > haystackLength)
return -1;
for (int i = 0; i <= haystackLength - needleLength; i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
for (j = 1; j < needleLength; j++) {
if (haystack.charAt(i + j) != needle.charAt(j))
break;
}
if (j == needleLength)
return i;
}
}
return -1;
}
}
最新文章
- 解决jquery1.9不支持browser对象的问题||TypeError: $.browser is undefined
- hbase-site.xml 配置详解
- 先装.net后装iis的问题
- Linux中/proc目录下文件详解
- Linux 下从头再走 GTK+-3.0 (六)
- [转] - QBuffer类参考
- [转载] 跳表SkipList
- 深入理解计算机系统第二版习题解答CSAPP 2.11
- Flink 另外一个分布式流式和批量数据处理的开源平台
- 【Demo 0003】Android 事件
- 百度cdn资源公共库共享及常用开发接口
- Android中的数据持久化机制
- &#127827; redux示例 &#127827;
- js 基本包装类型 String
- Python学习之旅(二十九)
- GO-time.after 用法
- SpringBoot-整合@transactional注解
- es6比es5节省代码的地方总结
- [EffectiveC++]item23:Prefer non-member non-friend functions to member functions
- 专题实验 Toad 用户的创建与管理( 包括 role 等 )