LeetCode-实现strStr()
LeetCode-实现strStr()
Table of Contents
1 Easy-实现strStr()
1.1 题目描述
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
1.2 示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
1.3 示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
1.4 说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
2 自己的答案
2.1 思路
- 在haystack字符串中找到与needle[0]相同的字符,从这个字符开始,从haystack中取出与needle长度相同的字符串.
- 比较needle和取出的子字符串,如果相同,则返回当前索引.否则不存在,返回-1.
- 当needle为空字符串时候,返回0.
2.2 代码
package algorithm.easy; public class StrStr { public static int solution(String haystack, String needle) { if (needle.equals("")) { return 0; } int nLen = needle.length(); for (int i = 0; i < haystack.length(); i++) { // 如果needle字符串的第一个字符与haystack的某个位置的字符相同时候 if (haystack.charAt(i) == needle.charAt(0)) { // 取出haystack当前位置起始的,长度与needle相同的子字符串 // 如果长度超出范围,不存在 if (i + nLen > haystack.length()) { return -1; } String compare = haystack.substring(i, i + nLen); if (needle.equals(compare)) { return i; } } } return -1; } public static void main(String[] args) { String a = "aaaaa"; String b = "bba"; String c = "hello"; String d = "ll"; System.out.println(solution(a,b)); System.out.println(solution(c,d)); } }

浙公网安备 33010602011771号