计算出第一个文本中包含第二个文本每个单词的最短文本


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;

public class solution {
    @Test
    public void testFunc(){
        String longStr = "i have a dream i am a human you can have dream too";
        String shortStr = "i you am";
        int res = shortDistance(longStr, shortStr);
        System.out.println("res: "+res);
        
    }
//    计算出第一个文本中包含第二个文本每个单词的最短文本
    public int shortDistance(String longStr, String shortStr){
        String[] longArr = longStr.split("( ){1,}");
        String[] shortArr = shortStr.split("( ){1,}");
        HashMap<String, Integer> map = new HashMap<String,Integer>();
        for(String ele:shortArr){
            if(map.containsKey(ele)){
                map.put(ele, map.get(ele)+1);
            }else{
                map.put(ele, null);
            }
        }
        int res=longArr.length+1;
        for(int i=0;i<longArr.length;i++){
            if (map.containsKey(longArr[i])) {
                map.put(longArr[i], i);
                Set<Entry<String, Integer>> entrySet = map.entrySet();
                int minIndex=longArr.length;
                int maxIndex = -1;
                for(Entry<String, Integer> entry:entrySet){
                    Integer index = entry.getValue();
                    if (index==null) {
                        minIndex=longArr.length;
                        maxIndex = -1;
                        break;
                    }
                    if (index<minIndex) {
                        minIndex=index;
                    }
                    if (index>maxIndex) {
                        maxIndex = index;
                    }
                }
                res = Math.min(res, Math.abs(maxIndex-minIndex)+1);
            }
        }
        return res;
    }
    
}

猜你喜欢

转载自blog.csdn.net/wwzheng16/article/details/81040069