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