本文共 1381 字,大约阅读时间需要 4 分钟。
求一个字符串中,某一个子串它的下标,如果有,则返回这个子串首次出现的下标,如果没有,就返回-1
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2 Example 2:Input: haystack = "aaaaa", needle = "bba"
Output: -1
【解一】
public class demo{ public static int strStr(String s1,String s2){ String s3 = ""; int len = 0; int index = 0; int result = 0; int i = 0; int j = 0; if(s2.length()>s1.length()) { return -2; }else if(s2=="") { return -3; }else { for(;i=0){ System.out.println("该字符串出现的第一个位置为:"+(result-s2.length())); }else if(result==-3){ System.out.println("该字符串出现的第一个位置为:"+0); }else { System.out.println("请输入正确的字符串"); } }}
【解二】
public class demo{ public static void main(String[] args) { String hayStack = "helohello"; String needle = "ello"; int pl = 0; int index = 0; for (int i = 0; i < hayStack.length(); i++) { index = i; String str = ""; for (int j = i; str.length() < needle.length(); j--) { if (j >= 0) { str = hayStack.charAt(j) + str; }else { break; } } if (needle.equals(str)) { pl = 1; break; }else { pl = 0; } } if (needle == "") { System.out.println("0"); }else if (pl == 1) { System.out.println(index+1-needle.length()); }else { System.out.println(-1); } } }
转载地址:http://niazi.baihongyu.com/