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

28. Implement strStr() - Easy

时间:2018-12-17 20:17:53      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:equals   return   not   interview   java   dex   imp   http   index   

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

 

用substring()来判断

注意:Java 7中,string.substring()的时间复杂度是O(n),n为子串长度

time: O(mn), space: O(1)  -- m: needle length, n: haystack length

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

 

28. Implement strStr() - Easy

标签:equals   return   not   interview   java   dex   imp   http   index   

原文地址:https://www.cnblogs.com/fatttcat/p/10133131.html

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