当前位置: 代码迷 >> 综合 >> LeetCode-Java-28. Implement strStr()
  详细解决方案

LeetCode-Java-28. Implement strStr()

热度:85   发布时间:2023-12-16 09:15:01.0

题目

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 haystack, String needle) {if(haystack==null||needle==null)return -1;if((needle.length()==0&&haystack.length()==0)||needle.length()==0)return 0;int hlen = haystack.length();int nlen = needle.length();int i=0,j=0,k=0;while(hlen!=i&&nlen!=j&&hlen>=i&&nlen>=j){char h = haystack.charAt(i);char n = needle.charAt(j);if(h==n){i++;j++;}else{k++;i=k;j=0;}}if(nlen!=j)return -1;elsereturn i-j;}
}
  相关解决方案