问题描述
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
算法描述
String类包含有很多的方法,对这道题,我们要匹配字符串,需要两步,第一步找到开始的索引,第二步就是判断索引之后的needle.length()个元素是否和needle相等,完成这两个任务题目就解决了,方法参考substring()的截取功能。
String类常用方法参考(图片来源网络,侵删):
实现代码和注释
class Solution {
public static int strStr(String haystack, String needle) {
if(needle.equals("")) //needle为空时的情况
return 0;
if(haystack.equals("")) //haystack为空的情况
return -1;
for(int i = 0; i <= haystack.length() - needle.length(); i++){
//通常不判断倒数的几个元素,因为它的长度不满足匹配条件
if(haystack.charAt(i) == needle.charAt(0) && haystack.substring(i, i + needle.length()).equals(needle)){
/**
*情况是这样的,haystack.charAt(i) == needle.charAt(0)先匹配看needle的
*第一个元素,第一个元素都不满足那就没得说了,直接为-1;能找到第一个元素后,
*haystack.substring(i, i + needle.length()).equals(needle)截取后面几
*个字符,然后与needle进行匹配,substring时截取相关索引元素的方法
*/
return i;
}
}
return -1;
}
}