题目描述:

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;
}
}

最新文章

  1. 解决jquery1.9不支持browser对象的问题||TypeError: $.browser is undefined
  2. hbase-site.xml 配置详解
  3. 先装.net后装iis的问题
  4. Linux中/proc目录下文件详解
  5. Linux 下从头再走 GTK+-3.0 (六)
  6. [转] - QBuffer类参考
  7. [转载] 跳表SkipList
  8. 深入理解计算机系统第二版习题解答CSAPP 2.11
  9. Flink 另外一个分布式流式和批量数据处理的开源平台
  10. 【Demo 0003】Android 事件
  11. 百度cdn资源公共库共享及常用开发接口
  12. Android中的数据持久化机制
  13. &#127827; redux示例 &#127827;
  14. js 基本包装类型 String
  15. Python学习之旅(二十九)
  16. GO-time.after 用法
  17. SpringBoot-整合@transactional注解
  18. es6比es5节省代码的地方总结
  19. [EffectiveC++]item23:Prefer non-member non-friend functions to member functions
  20. 专题实验 Toad 用户的创建与管理( 包括 role 等 )

热门文章

  1. MacOS10.9获取Android源码不完全笔记(2014)
  2. jQuery ajax 实现分页 kkpager插件
  3. win7下以兼容模式安装oracle10g
  4. 多智能体仿真环境 NetLogo
  5. 用JavaScript获取页面上被选中的文字的技巧
  6. 移动web开发入门级
  7. 国外程序员整理的 C++ 资源大全
  8. linux和window下mkdir函数
  9. JavaWeb学习总结(四十八)——模拟Servlet3.0使用注解的方式配置Servlet
  10. SOCKS5协议