LeetCode算法入门- Implement strStr() -day22
- 题目描述
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().
-
题目分析:
通过两个for循环来实现 -
Java实现:
class Solution {public int strStr(String haystack, String needle) {if(needle.length() == 0){return 0;}for(int i = 0 ; ; i++){for(int j = 0; ; j++){//如果长度相同,说明完全匹配了if(j == needle.length()){return i;}//下面代码其实就是for循环省去的约束部分if(i + j == haystack.length()){return -1;}//用来判断对应的字符是不是相同if(haystack.charAt(i + j) != needle.charAt(j)){break;}}}}
}