BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #50178同步于 2016/5/11
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

小白leetcode第三题求教

hotpot
2016/5/11镜像同步44 回复
题目是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==“”这个情况,怎么还有这个错误呢,求帮忙看一下
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
chenxiansf机器人#1 · 2016/5/11
话说==是比较引用的吧 【 在 hotpot (沙漏吃火锅) 的大作中提到: 】 : 题目是Longest Substring Without Repeating Characters : 我的答案是 : public class Solution { : ...................
wht机器人#2 · 2016/5/11
就算没错也会超时,双层循环过不了的,换种思路吧 【 在 hotpot (沙漏吃火锅) 的大作中提到: 】 : 题目是Longest Substring Without Repeating Characters : 我的答案是 : public class Solution { : ...................
dss886机器人#3 · 2016/5/11
直接看LeetCode的DIscuss吧,按most votes排序 另外新手不建议按序号123做。。。点击难度先从easy开始做,或者点某一个标签比如array,从易到难做
fuxuemingzhu机器人#4 · 2016/5/11
说得对 。看到 arraylist 就估计会超时 【 在 wht (【zybd】【lgkk】|谁与争锋|仙剑永恒) 的大作中提到: 】 : 就算没错也会超时,双层循环过不了的,换种思路吧
twinkle1437机器人#5 · 2016/5/11
if(s=="")改为 if(s.equals("")) 参考: http://stackoverflow.com/questions/767372/java-string-equals-versus 另外同觉得LZ写得有点复杂,可以看看Discuss,里面应该有优化的解法。
maxpowergo机器人#6 · 2016/5/12
我记得当时我是用哈希表写的这道题,当时效率好像还挺高 发自「贵邮」
hayabusa机器人#7 · 2016/5/12
【 在 chenxiansf 的大作中提到: 】 : 话说==是比较引用的吧 不是 的吧,==比较两个是否是同一个对象,equal比较两个对象的值是否相等
VictorLees机器人#8 · 2016/5/12
楼主贴代码为啥不用论坛自带的格式啊
chftianxia机器人#9 · 2016/5/12
这 s=""表示s是一个对象,它的值啥都没有;但是如果s=null呢??s连对象都没初始化~~所以LZ把s=""改成s==null||s.length()==0应该就不会报这个错了吧 【 在 hotpot 的大作中提到: 】 : 题目是Longest Substring Without Repeating Characters : 我的答案是 : public class Solution { : ...................