提问人:Prakhar Singh 提问时间:7/2/2021 更新时间:7/3/2021 访问量:72
最长的 K 个唯一字符子字符串 (NULL POINTER EXCEPTION ERROR) [duplicate]
Longest K unique characters substring (NULL POINTER EXCEPTION ERROR) [duplicate]
问:
请在我的代码中找到错误
public int longestkSubstr(String s, int k) {
// code here
if(s.length()==0)
return 0;
int i=0,j=0;
int ans=-1;
Map<Character,Integer> map=new HashMap<>();
while(j<s.length()){
map.put(s.charAt(j),map.getOrDefault(s.charAt(i),0)+1);
if(map.size()<k)
j++;
else if(map.size()==k){
ans=Math.max(ans,j-i+1);
j++;
}
else if (map.size()>k){
while(map.size()>k){
map.put(s.charAt(i),map.get(s.charAt(i))-1);
if(map.get(s.charAt(i))==0)
map.remove(s.charAt(i));
i++;
} j++;}
}
return ans;`}
运行时错误: 线程“main”中的运行时 ErrorException java.lang.NullPointerException 在 Solution.longestkSubstr(File.java:43)
答:
0赞
Md. Faisal Habib
7/3/2021
#1
Map<Character, Integer> map = new HashMap<>();
在这里,你已将 Map 声明为 <Character, Integer>。整数类型对象的值可以为 null。
map.put(s.charAt(i),map.get(s.charAt(i))-1);
在 “” 中,即使返回 NULL,您的代码仍在尝试对其进行算术运算。map.get(s.charAt(i))-1
map.get(s.charAt(i))
这就是显示java.lang.NullPointerException的原因。
Map.get()
当键不存在时返回 null。整数 (autoboxed type) 不能自动拆箱为 int,因此 它抛出 NullPointerException。
溶液:
无论您在哪里使用,请尝试检查它是否为 null。map.get
在你的情况下,它可能如下,
if( map.get(s.charAt(i)) != null) map.put(s.charAt(i), map.get(ch) - 1);
if (map.get(s.charAt(i)) != null && map.get(s.charAt(i)) == 0)
请查看以下参考资料,以了解有关 Map 的方法和其他用途的更多信息get()
祝您编码愉快!
评论
longestkSubstr
s