Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

Constraints:

haystack and needle consist only of lowercase English characters.

实现代码

实现的关键就是使用substring()方法,将整个字符串分成与目标字符串的长度相同的小段,然后使用equals方法比较,如果有相同的,则返回开始的角标

 1 package easy;
2
3 class SolutionStr{
4 public int strStr(String hystack,String needle){
5 int len1 = hystack.length();
6 int len2 = needle.length();
7 if(len2 > len1){
8 return -1;
9 }
10 if(len2 == 0){
11 return 0;
12 }
13 for(int i = 0;i < len1 - len2 + 1; ++i){
14 if(hystack.substring(i,i+len2).equals(needle)){
15 return i;
16 }
17 }
18 return -1;
19 }
20 }
21 public class ImplstrStr {
22 public static void main(String[] args) {
23 SolutionStr solution = new SolutionStr();
24 System.out.println(solution.strStr("leetcode","ee"));
25 }
26 }

最新文章

  1. python多行字符串
  2. sqlserver2012 表分区
  3. HTML5 div+css导航菜单
  4. 【目录】微软Infer.NET机器学习组件文章目录
  5. Excel如何查找名字重复的数据
  6. 性能测试问题_Mysql数据库服务器的CPU占用很高
  7. (转)DEDECMS模板原理、模板标签学习 - .Little Hann
  8. win7安装 Apache2.2 PHP5.3 MySQL5.6
  9. 图解IntelliJ IDEA 13版本对Android SQLite数据库的支持
  10. 我的Android 4 学习系列之Intent 和 Broadcast Reciever
  11. Linux指令--mv
  12. 七牛云图片的存储与处理--基于node
  13. sczd
  14. CS页面-Asp.net+Spring.Net.Framework--SNF快速开发平台3.0
  15. FastDFS分布式文件系统设计原理
  16. 自定义shell命令--闪烁的字母(PIL实现)
  17. 通过logstash收集mysql慢查询日志转换为json
  18. 243. Shortest Word Distance 最短的单词index之差
  19. HTML 5入门知识(四)
  20. chef简介

热门文章

  1. 深入理解Java虚拟机(八)——类加载机制
  2. 移动端和PC端区分
  3. 看我如何用微信上线CobaltStrike
  4. oracle DG搭建
  5. Eclipse的基本设置与使用
  6. Sql Server 数据把列根据指定的内容拆分数据
  7. 实验4 汇编应用编程和c语言程序反汇编分析
  8. Java进阶专题(十九) 消息中间件架构体系(1)-- ActiveMQ研究
  9. 网站开发学习Python实现-Django学习-自学注意(6.1.3)
  10. OpenSNS后台文件上传漏铜分析