public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int a = solution.ans("helolo","ll");
System.out.println(a);
}
public int ans(String s, String t) {
if (!s.contains(t)) return -1;
//记录出现的位置
int temp = 0, i = 0, j = 0;
char[] arrS = s.toCharArray();
char[] arrT = t.toCharArray();
//遍历查找位置
while (i < arrS.length && j < arrT.length) {
if (arrS[i] == arrT[j]) {
temp += 1;
i++;
j++;
} else {
temp = 0;
i++;
j = 0;
}
if (temp == arrT.length) return i - arrT.length;
}
return -1;
}
}
第二个字符串在第一个字符串中出现的位置
最新推荐文章于 2023-11-01 19:44:52 发布