strStr()javaを実現するためのLeetcodeダブルポインタ

タイトルの説明
strStr()関数を実装します。
干し草の山の文字列と針の文字列が与えられた場合、干し草の山の文字列内の針の文字列の最初の位置を見つけます(0から開始)。存在しない場合は、-1を返します。
例1:
入力:haystack = "hello"、needle = "ll"
出力:2

アイデア:
部分文字列の最初の文字が針文字列の最初の文字と同じである場合にのみ、比較する必要があります。次に、文字ごとに比較し、一致しなくなるとすぐに終了します。不一致が見つかると、バックトラックが開始されます。pnポインタはpn = pn-curr_lenの位置ではなくpn = pn-curr_len +1の位置に移動することに注意してください。

コード:

class Solution {
    
    
    public int strStr(String haystack, String needle) {
    
    
        int lenH = haystack.length();
        int lenN = needle.length();
        if(lenN == 0){
    
    
            return 0;
        }
        int start = 0;
        while(start < lenH - lenN +1){
    
    
            while(start < lenH - lenN +1 && haystack.charAt(start) != needle.charAt(0)){
    
    
                start++;
            }
            int start_n = 0;
            int currentlen = 0;
            while(start < lenH && start_n < lenN && haystack.charAt(start) == needle.charAt(start_n)){
    
    
                start_n++;
                start++;
                currentlen++;
            }
            if(currentlen == lenN){
    
    
                return start - currentlen;
            }
            start = start - currentlen +1;
        }
        return -1;

    }
}

おすすめ

転載: blog.csdn.net/stonney/article/details/112140824