返回信息流题目是Longest Substring Without Repeating Characters
我的答案是
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s==""){
return 0;
}
else{
HashMap<ArrayList<Character>,Integer>res=new HashMap<ArrayList<Character>, Integer>();
for (int i = 0; i < s.length(); i++) {
ArrayList<Character>tem=new ArrayList<Character>();
for (int j = i; j < s.length(); j++) {
if (tem.contains(s.charAt(j))) {
res.put(tem, tem.size());
break;
}else{
tem.add(s.charAt(j));
}
}
}
ArrayList<Map.Entry<ArrayList<Character>,Integer>> listEntry=new ArrayList<Map.Entry<ArrayList<Character>,Integer>>(res.entrySet());
Collections.sort(listEntry,new Comparator<Map.Entry<ArrayList<Character>,Integer>>(){
public int compare(Map.Entry<ArrayList<Character>,Integer>o1,Map.Entry<ArrayList<Character>,Integer>o2){
return o2.getValue()-o1.getValue();
}
});
return listEntry.get(0).getValue();
}
}
}
run code没有问题。但是在提交的时候报“Line 30: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0”这个错误。因为我已经考虑了s==“”这个情况,怎么还有这个错误呢,求帮忙看一下
这是一条镜像帖。来源:北邮人论坛 / java / #50178同步于 2016/5/11
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
小白leetcode第三题求教
hotpot
2016/5/11镜像同步44 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
话说==是比较引用的吧
【 在 hotpot (沙漏吃火锅) 的大作中提到: 】
: 题目是Longest Substring Without Repeating Characters
: 我的答案是
: public class Solution {
: ...................
就算没错也会超时,双层循环过不了的,换种思路吧
【 在 hotpot (沙漏吃火锅) 的大作中提到: 】
: 题目是Longest Substring Without Repeating Characters
: 我的答案是
: public class Solution {
: ...................
直接看LeetCode的DIscuss吧,按most votes排序
另外新手不建议按序号123做。。。点击难度先从easy开始做,或者点某一个标签比如array,从易到难做
说得对 。看到 arraylist 就估计会超时
【 在 wht (【zybd】【lgkk】|谁与争锋|仙剑永恒) 的大作中提到: 】
: 就算没错也会超时,双层循环过不了的,换种思路吧
if(s=="")改为 if(s.equals(""))
参考:
http://stackoverflow.com/questions/767372/java-string-equals-versus
另外同觉得LZ写得有点复杂,可以看看Discuss,里面应该有优化的解法。
【 在 chenxiansf 的大作中提到: 】
: 话说==是比较引用的吧
不是 的吧,==比较两个是否是同一个对象,equal比较两个对象的值是否相等
这 s=""表示s是一个对象,它的值啥都没有;但是如果s=null呢??s连对象都没初始化~~所以LZ把s=""改成s==null||s.length()==0应该就不会报这个错了吧
【 在 hotpot 的大作中提到: 】
: 题目是Longest Substring Without Repeating Characters
: 我的答案是
: public class Solution {
: ...................