From 90bd09b1c1fc742b05da5418ff783d1ef6ccda40 Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Tue, 20 Apr 2021 10:30:28 +0800 Subject: [PATCH] =?UTF-8?q?28:=E5=AE=9E=E7=8E=B0=20strStr()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode/editor/cn/ImplementStrstr.java | 48 +++++++++++++++++-- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/LeetCode/src/main/java/leetcode/editor/cn/ImplementStrstr.java b/LeetCode/src/main/java/leetcode/editor/cn/ImplementStrstr.java index 5449ef3..1100553 100644 --- a/LeetCode/src/main/java/leetcode/editor/cn/ImplementStrstr.java +++ b/LeetCode/src/main/java/leetcode/editor/cn/ImplementStrstr.java @@ -46,19 +46,57 @@ // 👍 800 👎 0 package leetcode.editor.cn; + //28:实现 strStr() -public class ImplementStrstr{ +public class ImplementStrstr { public static void main(String[] args) { //测试代码 Solution solution = new ImplementStrstr().new Solution(); +// solution.strStr("aaaaa", "bba"); +// solution.strStr("mississippi", "mississippi"); + System.out.println(solution.strStr("mississippi", "issip")); } + //力扣代码 //leetcode submit region begin(Prohibit modification and deletion) -class Solution { - public int strStr(String haystack, String needle) { - return haystack.indexOf(needle); + class Solution { + public int strStr(String haystack, String needle) { +// return haystack.indexOf(needle); + if ("".equals(needle)) { + return 0; + } + if ("".equals(haystack)) { + return -1; + } + char[] hay = haystack.toCharArray(); + char[] need = needle.toCharArray(); + int hSize = hay.length; + int nSize = need.length; + int result = 0; + int index = -1; + for (int i = 0; i <= hSize - nSize; i++) { + int temp = i; + for (char c : need) { + if (hay[i] == c) { + if (result == 0) { + index = i; + } + result++; + i++; + } else { + result = 0; + index = -1; + break; + } + } + i = temp; + if (result == nSize) { + break; + } + } + return index; + } } -} //leetcode submit region end(Prohibit modification and deletion) } \ No newline at end of file