年后第一题,身体是革命的本钱,过年没把身体照顾好,导致好多天不能学习。
>_<
题目原址
https://leetcode.com/problems/implement-strstr/description/
题目描述
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
Example2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
解题思路
这道题解题过程还是相对简单的。
- 第一步:首先要得到两个字符串的长度
- 第二步:嵌套for循环
- (1) 如果needle字符串的下标值等于needle字符串的长度,就说明找到了想要返回的下标值,否则执行(2)
- (2) 如果i+j的值等于haystack字符串的长度,那就说明没有找到想要返回的下标值,这条语句的含义就是,当haystack字符串剩余的元素个数小于needle字符串剩余元素个数,那一定没有符合条件的下标值,否则执行(3)
- (3) 依次比较haystack字符串中的元素与needle字符串中的元素是否相等,如果不相等跳出内层循环
AC代码
class Solution {
public int strStr(String haystack, String needle) {
int length1 = haystack.length();
int length2 = needle.length();
for(int i = 0; ; i++) {
for(int j = 0; ; j++) {
if(j == length2) return i;
if(i + j == length1) return -1;
if(haystack.charAt(i + j) != needle.charAt(j)) break;
}
}
}
}
感谢
https://leetcode.com/problems/implement-strstr/discuss/12807/Elegant-Java-solution