[算法]字符串查找问题

题目:
有长度为n的字符数组[‘a’, ‘g’, ‘c’, ‘f’]和字符串string=“abcdfegafcbcdkdjkaldjfasd;lfadsf”,设计算法获取到在字符串string中出现连续n个字符都在字符数组集合中的位置。顺序无要求,不允许重复。
代码:

  public static void main(String[] args) {
        Stack stack = new Stack();
       // List list = new ArrayList();
       // list.contains()
        Stack stackBak = new Stack();
        HashMap<Object,Object> hs = new HashMap<>();
        HashMap<Object,Object> bak = new HashMap<>();
        char[] chars = new char[] { 'a', 'g', 'c', 'f' };
        for (int i =0;i<chars.length;i++){
            hs.put(chars[i],i);
            stack.push(chars[i]);
        }
    String  string = new String("abcdfegafcbcdkdjkaldjfasd;lfadsf");
    for (int i =0 ;i<string.length() ;i++){

        if (hs.containsKey(string.charAt(i))){
            hs.remove(string.charAt(i));
            bak.put(string.charAt(i),i);
        }else{
            hs.putAll(bak);
            bak.clear();
        }
        if (hs.size()==0){
            System.out.println("已经查找到,位于第:"+(i-bak.size())+"-"+i);
            break;
        }
    }

    }

你可能感兴趣的:(java)