一道從室友那兒偷來的51信用卡筆試題-判斷字符串A是否包含字符串B

這裏寫圖片描述

目前思路是分別掃描兩個字符串得到兩個map


    boolean judge(String str1,String str2){
        HashMap<Character,Integer> map1=new HashMap<>();
        HashMap<Character,Integer> map2=new HashMap<>();
        for(int i=0;i<str1.length();i++){
            if(map1.containsKey(str1.charAt(i))){
                map1.put(str1.charAt(i),map1.get(str1.charAt(i))+1);
            }
            else{
                map1.put(str1.charAt(i),1);
            }
        }
        for(int i=0;i<str2.length();i++){
            if(map2.containsKey(str2.charAt(i))){
                map2.put(str2.charAt(i),map2.get(str2.charAt(i))+1);
            }
            else{
                map2.put(str2.charAt(i),1);
            }
        }
        for(Map.Entry<Character,Integer> entry :map2.entrySet()){
            if(map1.containsKey(entry.getKey())){
                if(map1.get(entry.getKey())>=entry.getValue()){
                    continue;
                }
                else
                    return false;
            }

        }
        return true;

    }
    public static void main(String[] args) {
        contains s=new contains();
        Scanner scanner=new Scanner(System.in);
        String str1=scanner.nextLine();
        String str2=scanner.nextLine();
        boolean ans=s.judge(str1,str2);
        if(ans){
            System.out.println("true");
        }
        else
            System.out.println("false");
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章