LeetCode Implement strStr()
来源:互联网 发布:女生必知 编辑:程序博客网 时间:2024/06/01 08:17
问题网址:https://leetcode.com/problems/implement-strstr/description/
问题描述:
实现strStr()。
在needle中返回第一haystack的指数,如果haystack不是needle的一部分,则返回-1。
问题例子:
Example 1:Input: haystack = "hello", needle = "ll"Output: 2Example 2:Input: haystack = "aaaaa", needle = "bba"Output: -1
这个问题没什么难度,下面是一个简短的Java解法
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; } }}
阅读全文