码迷,mamicode.com
首页 > 其他好文 > 详细

172.Implement strStr()

时间:2018-09-17 17:45:33      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:ica   class   div   ++   length   stack   The   during   子串   

题目:

Implement strStr().

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

返回haystack中第一次出现针的索引,如果needle不是haystack的一部分,则返回-1。

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.

当needle是空字符串时我们应该返回什么? 在面试中这是一个很好的问题。

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().

出于此问题的目的,当needle为空字符串时,我们将返回0。 这与C的strstr()和Java的indexOf()一致。

解答:

 1 class Solution {
 2     public int strStr(String haystack, String needle) {
 3         int l1=haystack.length(), l2=needle.length();
 4         if(l2==0)
 5             return 0;
 6         if(l1<l2)
 7             return -1;
 8         for(int i=0;i<=l1-l2;i++){
 9             if(haystack.substring(i,i+l2).equals(needle))
10                 return i;
11         }
12         return -1;
13     }
14 }

详解:

如果needle为空,返回0

如果haystack的长度小于needle,返回-1

如果haystack从i到i+needle的长度的子串=needle,返回i

 

172.Implement strStr()

标签:ica   class   div   ++   length   stack   The   during   子串   

原文地址:https://www.cnblogs.com/chanaichao/p/9662840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!