(Java)leetcode-28 Implement strStr()

题目

【实现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
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().

思路

暴力搜索

代码

class Solution {
        public int strStr(String s, String t) {
        if (t.isEmpty()) return 0; // 边界条件: "",""=>0  "a",""=>0
        for (int i = 0; i <= s.length() - t.length(); i++) { 
            for (int j = 0; j < t.length() && s.charAt(i + j) == t.charAt(j); j++)  
                if (j == t.length() - 1) //匹配 结束再返回s中的匹配起点 
                	return i;
        }
       // 搜索无果则返回-1
        return -1;
    }
}

提交结果

Runtime: 2 ms, faster than 90.98% of Java online submissions for Implement strStr().
Memory Usage: 38.5 MB, less than 31.25% of Java online submissions for Implement strStr().

发布了143 篇原创文章 · 获赞 45 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/z714405489/article/details/89214057