Implement strStr()

本文介绍了一种在Java中实现字符串匹配的方法,提供了两种解决方案:一种是直接使用Java内置的String类方法,另一种是通过手动实现字符串匹配算法。

题目

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


思路分析

        阅读题目可是,其实问题要求的就是字符串的模式匹配问题。

        可以用三种解法:

        1.直接调用Java中String类中自带的方法haystack.indexOf(needle);可以直接判断一个字符串中是否包含另一个字符串。

        2.直接求解法。比较简单,注意的是对特殊输入的判断处理,需要用到".equals(str)",而不是str==null。参考

     

直接调用String类方法:

class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}

直接求解法:

class Solution {
    public int strStr(String haystack, String needle) {
        if("".equals(haystack)&&"".equals(needle))
            return 0;
	    else if("".equals(haystack) && !"".equals(needle))
			 return -1;
	    else if(!"".equals(haystack) && "".equals(needle))
			 return 0;
		int len1=haystack.length();
		int len2=needle.length();
		
		if(len1<len2)
			return -1;
		
		int i=0,j,k;
		while(i<len1){
			
			int tmp=len1-i;
			
			if(len1-i>=len2){
				
				for(j=0,k=i;j<len2;j++,k++){
					
					if(needle.charAt(j)!=haystack.charAt(k)){
						
						break;
					}
				}
				if(j==len2)
					return i;
				i++;
			}
			else
				return -1;
		}
		
		return -1;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值