28. 實現 strStr()-字串-簡單
阿新 • • 發佈:2020-07-21
問題描述
實現strStr()函式。
給定一個haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:
當needle是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當needle是空字串時我們應當返回 0 。這與C語言的strstr()以及 Java的indexOf()定義相符。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-strstr
解答
class Solution { public int strStr(String haystack, String needle) { int len1 = haystack.length(); int len2 = needle.length(); if(len2 > len1)return -1; if(len2 == 0)return 0; for(int i = 0; i < len1 - len2 + 1; ++i)if(haystack.charAt(i) == needle.charAt(0)) if(haystack.substring(i, i + len2).equals(needle)) return i; return -1; } }