【题意】

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

【思路】

一開始我是用 HashMap 做的,然后就在考虑 字母做key还是下标做key,总之比較麻烦。

后来看到网上普遍用数组来实现 HashMap 的功能。感觉还是挺新的。

至于为什么数组的大小设为256,始终想不明确。我查了下ASCII码表,上面也仅仅有127个字符。A~Z是65~90,a~z是97~112。

以下的代码我认为是已经相当简洁了。參考出处:JavaC++。大家共同学习。

public class Solution {
public int lengthOfLongestSubstring(String s) {
int len = s.length();
if (s == null || len == 0) return 0; int[] table = new int[256];
Arrays.fill(table, -1); int maxlen = 1;
int begin = 0, end = 1;
table[s.charAt(0)] = 0; //important!
while (end < len) {
char endch = s.charAt(end);
if (table[endch] >= begin) {
begin = table[endch] + 1;
}
table[endch] = end;
maxlen = Math.max(maxlen, end-begin+1);
end++;
} return maxlen;
}
}

上面代码有下面优点:它推断有没有反复是通过当前字母在table中的值是不是比子串的開始位置大,这样就不用每次出现反复字母后都须要把之前的字符在table中的值又一次设为-1。

最新文章

  1. ubuntu git 使用
  2. Servlet Request的 getInputStream() getReader() getParameter()
  3. 35. Search Insert Position
  4. DEV控件,PopupContainerEdit,PopupContainerControl,TreeList,弹出控制问题
  5. AC日记——导弹拦截 洛谷 P1020 (dp+模拟)
  6. Incorrect key file for table &#39;/tmp/#sql_882_0.MYI&#39;; try to repair it
  7. SVN 命令行 精编版
  8. 局域网内sqldeveloper客户端连接oracle服务器
  9. MFC软件工程架构模型-模式窗口-非模式窗口
  10. angularjs表单
  11. mysql(4)—— 表连接查询与where后使用子查询的性能分析。
  12. 使用 Swoole 来加速你的 Laravel 应用
  13. ReactNative问题随记1 Exception in thread &quot;main&quot; java.lang.RuntimeException: gradle-2.14.1-all.zip
  14. python3 正则表达式点星问号(.*?)能不能匹配换行符?不能的话应该怎么写
  15. npm 常用命令 查看版本、安装、卸载
  16. [洛谷P1731][NOI1999]生日蛋糕(dfs)(剪枝)
  17. python学习之----爬取图片
  18. java web 中 filter 与 servlet的关系
  19. Java 将任意数组的任意两个位置的数据进行交换
  20. Java 基本数据类型 sizeof 功能

热门文章

  1. Java Itext 生成PDF文件
  2. 【BZOJ2762】[JLOI2011]不等式组(树状数组)
  3. Java中的overload(方法的覆写)
  4. Maven 学习(1)
  5. python2升级成python3
  6. 详解HashMap数据结构实现
  7. Centos6.7 编译安装 Apache PHP
  8. Find the build UUID in a Crash Report
  9. Docker是什么?可以用Docker做什么?
  10. 文章或者观点说说等点赞功能实现(thinkphp)