Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析
题目介绍
Implement strStr()
.
Return the index of the first occurrence of needle in haystack, or -1
if needle
is not part of haystack
.
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()
.
示例
Example 1:1
2Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:1
2Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:1
2Input: haystack = "", needle = ""
Output: 0
题解
字符串比较其实是写代码里永恒的主题,底层的编译器等处理肯定需要字符串对比,像 kmp 算法也是很厉害
code
1 | public int strStr(String haystack, String needle) { |