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

28. Implement strStr()

时间:2018-12-21 13:00:21      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:bst   nbsp   com   highlight   string   aaa   index   png   hello   

28. Implement strStr()

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

笨方法1:
class Solution {
    public int strStr(String haystack, String needle) {
       if(needle==""||needle==null){
           return 0;
       } 
       else return haystack.indexOf(needle);
    }
}

  直接用indexOf

方法2:

class Solution {
    public int strStr(String haystack, String needle) {
        int res = 0;
        if(needle==""||needle==null){
          return res;
       } 
        else{
            int n = needle.length();
            int i = 0;
            for(; i< haystack.length()-n; i++){
                if(haystack.substring(i,i+n).equals(needle)){
                    res = i;
                    break;
                }
            }
            if(i>=haystack.length()-n){
                res = -1;
            }
        }
        return res;
    }
}

  奇怪的是当输入为("","")时,leetcode会报错,但是eclipse输出还是0,不知道为什么

技术分享图片

 

28. Implement strStr()

标签:bst   nbsp   com   highlight   string   aaa   index   png   hello   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10153583.html

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