這題是要呈現 indexOf 的邏輯,如果不匹配則會返回 -1。
LeetCode 題目連結
https://leetcode.com/problems/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
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
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.Accept 作法
這題表面上好像很好寫,但很容易遺漏一些 case ,要小心。
Runtime: 0 ms
Memory: 38.6 MB
Java
Runtime: 0 ms
Memory: 38.6 MB
class Solution {
    public int strStr(String haystack, String needle) {
        if(needle.length() == 0 && haystack.length() == 0)
            return 0;
        if(needle.length() == 0){
            return 0;
        }
        
        if(needle.length() > haystack.length()){
            return -1;
        }
        
         if(needle.equals(haystack)){
            return 0;
        }
        
        int size = haystack.length() - needle.length();
        for(int i = 0;i <= size;i++){
           String result = haystack.substring(i,i+needle.length());
           if(result.equals(needle)){
               return i;
           } 
        }
        return -1;
    }
}
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。

沒有留言:
張貼留言