28.Find the Index of the First Occurrence in a String

来自WHY42
Riguz留言 | 贡献2024年2月19日 (一) 15:20的版本 (创建页面,内容为“=Description= {{LeetCode |id=find-the-index-of-the-first-occurrence-in-a-string |no=28 |difficulty=Easy |category=String |collection=Top 150 |title=Find the Index of the First Occurrence in a String |summary=Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.}} == State Machine == {{Submission|runtime=1ms|memory=41.15MB|rp=36.32|mp=87.80}} <syntaxhighlight lang="java">…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

Description

#28 Find the Index of the First Occurrence in a String Easy
String Top 150
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

State Machine

Runtime 1ms
Memory 41.15MB
class Solution {
    enum State {
        NOT_MATCHED,
        MATCHING,
    }
    public int strStr(String haystack, String needle) {
        State s = State.NOT_MATCHED;
        int start = -1;
        for(int i = 0; i < haystack.length(); i++) {
            switch(s) {
                case State.NOT_MATCHED: {
                    if(haystack.charAt(i) == needle.charAt(0)) {
                        if(needle.length() == 1) return i;
                        s = State.MATCHING;
                        start = i;
                        break;
                    } else {
                        break;
                    }
                }
                case State.MATCHING: {
                    if(haystack.charAt(i) != needle.charAt(i - start)) {
                        s = State.NOT_MATCHED;
                        i = start;
                        start = -1; 
                        break;
                    } else {
                        if(i - start + 1== needle.length()) return start;
                        break;
                    }
                }
                default: break;
            }
        }
        return -1;
    }
}