Java实现LeetCode_0028_ImplementStrStr
2023-09-14 08:58:08 时间
package javaLeetCode.primary;
import java.util.Scanner;
public class ImplementStrStr_28 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Please input a string(hayStack):");
String hayStack = input.next();
System.out.println("Please input a string(needle):");
String needle = input.next();
System.out.println(strStr_1(hayStack, needle));
}// end main()
/**
* 1. Find the same character in "haystack" as the first "needle" character.
* 2. Start with this character and move back in the "haystack" one by one against the characters in the "needle".
* */
/*
* Input: haystack = "hello", needle = "ll"
* Output: 2
* Input: haystack = "helollo", needle = "ll"
* Output: 4
* Input: haystack = "aaaaa", needle = "bba"
* Output: -1
*Input: haystack = "a", needle = ""
* Output: 0
* Input: haystack = "abcd", needle = "b"
* Output: 0
* */
public static int strStr_1(String hayStack, String needle) {
int i = 0;
boolean isInclude = false;
// Judge "needle" is valid.
if (needle.length()==0 || needle == null) {
return 0;
} // end if
if (needle.length() > hayStack.length()) {
return -1;
} else {
for (i = 0; i < hayStack.length(); i++) {
if (hayStack.charAt(i) == needle.charAt(0)&&(hayStack.length()-i>=needle.length())) {
int k = i;
isInclude = true;
for (int j = 1; j < needle.length(); j++) {
if (needle.charAt(j) == hayStack.charAt(++k)) {
isInclude = true;
} else {
isInclude = false;
break;
} // end if
} // end for
} else {
continue;
}//end if
if (isInclude == true) {
break;
} // end if
} // end for
} // end if
return i < hayStack.length() ? i : -1;
}// end strStr()
/**
* Use the method of string class.
* */
public static int strStr_2(String hayStack, String needle) {
return hayStack.indexOf(needle);
}// end strStr()
}//end ImplementStrStr_28
相关文章
- Java实现 LeetCode 823 带因子的二叉树(DP)
- Java实现 LeetCode 809 情感丰富的文字 (暴力)
- Java实现 LeetCode 767 重构字符串(ASCII的转换)
- Java实现 LeetCode 757 设置交集大小至少为2(排序+滑动窗口)
- Java实现 LeetCode 725 分隔链表(暴力)
- Java实现 LeetCode 720 词典中最长的单词(字典树)
- Java实现 LeetCode 717 1比特与2比特字符(暴力)
- Java实现 LeetCode 695 岛屿的最大面积(DFS)
- Java实现 LeetCode 647 回文子串(暴力)
- Java实现 LeetCode 609 在系统中查找重复文件(阅读理解+暴力大法)
- Java实现 LeetCode 565 数组嵌套(没有重复值的数组)
- Java实现 LeetCode 543. 二叉树的直径(遍历树)
- Java实现 LeetCode 522 最长特殊序列 II(查找最长的非子序列的长度)
- Java实现 LeetCode 521 最长特殊序列 Ⅰ(出题人:“就是喜欢看你们不敢相信那么简单,又不敢提交的样子。”)...
- Java实现 LeetCode 515 在每个树行中找最大值
- Java实现 LeetCode 513 找树左下角的值
- Java实现 LeetCode 481 神奇字符串
- Java实现 LeetCode 420 强密码检验器
- Java实现 LeetCode 354 俄罗斯套娃信封问题
- Java实现 LeetCode 226 翻转二叉树
- Java实现 LeetCode 138 复制带随机指针的链表
- Java实现 LeetCode 77 组合
- Java实现 LeetCode 23 合并K个排序链表
- Java实现 LeetCode 8 字符串转换整数(atoi)
- Java实现 LeetCode 4 寻找两个有序数组的中位数
- Java实现LeetCode 110. Balanced Binary Tree
- 【Java】java使用反射访问对象方法和成员变量