双指针
: 通过一个指针指向haystack
,一个指针指向needle
,不断移动指针向前走,若发现needle
指针指到字符串的尾部则说明相等
此时结束;若发现遍历到的某个字符不相等则需要回溯haystack
,并将needle
指针重置
package KTwoPointers;
/**
* @Author Zhou jian
* @Date 2020 ${month} 2020/5/3 0003 23:48
*/
public class Problem28 {
//通过两个指针
//不断遍历两个字符串
public int strStr(String haystack, String needle) {
if(haystack==null||needle==null) return -1;
if(haystack.equals("")&&needle.equals("")) return 0;
if(needle.equals("")) return 0;
//记录带匹配的字符串的指针
int indexHay = 0;
//记录
int indexNeed = 0;
//结果值
int result = -1;
//用于记录下次应该从哪个位置遍历
int last = 0;
//待匹配字符串遍历
while(indexHay<haystack.length()){
//待匹配字符串到大末尾说明这个结果可以
if(indexNeed==needle.length()){
return result;
}
//发现字符相等
if(haystack.charAt(indexHay)==needle.charAt(indexNeed)){
//发现从待比较字符串的第一位开始,记录此时在比较字符串中的位置
if(indexNeed==0){
result=indexHay;
}
//不断向前推进
indexHay++;
indexNeed++;
//若此时都到字符串尾部则页返回true
if(indexHay==haystack.length()&&indexNeed==needle.length()) return result;
}else{//不相等,则更新indexHay为result+1
//
indexNeed=0;//待匹配字符只能从第一个接着比
//待匹配字符从哪一位????
indexHay = last+1;
last=indexHay;
}
}
return -1;
}
}
滑动窗口/
package com.zj.IString;
import java.util.HashMap;
import java.util.Map;
/**
* Author jzhou7
* Date 2020/8/18
*/
public class Problem28 {
/**
* 滑动窗口方法
* @param haystack
* @param needle
* @return
* 给定一个 haystack 字符串和一个 needle 字符串,
* 在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。
* 如果不存在,则返回 -1。
* 这种求的是序列
*/
public int strStr(String haystack, String needle) {
if(needle==null) return -1;
if(needle.equals("")) return 0;
Map<Character,Integer> need = new HashMap<>();
Map<Character,Integer> window = new HashMap<>();
for(int i=0;i<needle.length();i++){
need.put(needle.charAt(i),need.getOrDefault(needle.charAt(i),0)+1);
}
int left = 0;
int right = 0;
int valid = 0;
while (right<haystack.length()){
// 不断扩大窗口
Character c = haystack.charAt(right);
right++;
if(need.containsKey(c)){
window.put(c,window.getOrDefault(c,0)+1);
if(window.get(c).equals(need.get(c))) valid++;
if(valid==need.size()) return left;
}
while((right-left)>=needle.length()){
Character d = haystack.charAt(left);
left++;
if(need.containsKey(d)) {
if (window.get(d).equals(need.get(d))) valid--;
window.put(d, window.get(d) - 1);
}
}
}
return -1;
}
public static void main(String[] args) {
Problem28 problem28 = new Problem28();
// "mississippi"
// "pi"
int i = problem28.strStr("mississippi", "pi");
System.out.println(i);
}
}