Leetcode题解之字符串(7) 实现strStr()

题目:https://leetcode-cn.com/problems/implement-strstr/description/

题目描述:

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

思路: 第一种和第二张虽然都是暴力破解的思想,但是第二张操作的比较漂亮。第一种和我本人写的比较符合。

第三种是程序员中金字塔顶端的大牛写的。高度体现了代码的简洁性和重用性。佩服佩服。

第四种:KMP算法。难度有点高。详情看这里:https://blog.csdn.net/liu940204/article/details/51318281

第五种解法。也很巧妙也是用暴力破解

解法1:
class Solution {
    public int strStr(String haystack, String needle) {
        	if(needle==null||needle.length()==0) {
			return 0;
		}
		if(needle.length()>haystack.length()) {
			return -1;
		}
		int n=haystack.length();
		int m=needle.length();
		for(int i=0;i<n;i++) {
			if(n-i<m) {
				return-1;
			}
			if(haystack.charAt(i)!=needle.charAt(0)) {
				continue;
			}
			for(int j=0;j<m;j++) {
				
				if(haystack.charAt(i+j)!=needle.charAt(j)) {
					break;
				}
				else if(j==m-1)
					return i;
				
			}
		/*	if(haystack.substring(i, i+m).equals(needle)) {
				return i;
			}*/
		}
		return -1;

    }
}

解法2:
class Solution {
    public int strStr(String haystack, String needle) {
        int h_length=haystack.length();
        int n_length=needle.length();
        char[] h = haystack.toCharArray();
        char[] n = needle.toCharArray();
        String s2=new String(n);
        for(int i=0;i<=h_length-n_length;i++){
                String s1=new String(h, i, n_length);
                if(s1.equals(s2))
                    return i;
        }
        return -1;
    }
}

解法3:
class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}
//新增 解法5:
class Solution {
    public int strStr(String haystack, String needle) {
       for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {

                if (j == needle.length()) return i;

                if (i + j == haystack.length()) return -1;
                
                if (needle.charAt(j) != haystack.charAt(i + j)) break;
            }
        }
    }
 
}

猜你喜欢

转载自blog.csdn.net/qq_34433210/article/details/84067712