刷题记录1

写leetcode 242.有效的字母异位词,碰到两个问题
1、map更新数据
2、java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)"

测试通过的代码

    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        String[] strS = s.split("");
        Map<String,Integer> map = new HashMap<String,Integer>();
        for(int i = 0,len = strS.length;i<len;i++){
            if(map.get(strS[i]) != null){
                map.put(strS[i], map.get(strS[i]) + 1);
                continue;
            }
            map.put(strS[i],1);
        }
        String[] strT = t.split("");
        for(int i = 0 ,len = strT.length;i<len;i++){
         Integer count = map.get(strT[i]);
         if (count == null || count <= 0) {
                return false;
            }
             map.put(strT[i], map.get(strT[i]) - 1);
        }
        return true;
    }

测试未通过的源代码部分截取

//  错误代码
// 1、使用下示方式更新map数据
map.get(strT[i]) = map.get(strT[i]) - 1;

// 2、运行时报NullPointerException ,下面应该是strT[i],而不是strT ...... 
 if(map.get(strT[i]) == null || map.get(strT) < 0){
                return false;
 }


更新题解
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()){return false;}
        int []cnt = new int[26];
        for(char c : s.toCharArray()){cnt[c-'a']++;} 
        for(char c : t.toCharArray()){cnt[c-'a']--;}
        for(int i : cnt){if(i!=0)return false;}
        return true;
    }
}

posted @ 2023-12-11 21:13  虚拟式  阅读(36)  评论(0)    收藏  举报