LeetCode OJ 3. Longest Substring Without Repeating Characters
2016-03-24 15:26
281 查看
题目大意
给定一个字符串,求出该字符串中最长不重复子串的长度。用Map接口(适用于UTF-8字符集):
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Solution ss = new Solution(); System.out.println(ss.lengthOfLongestSubstring("asadfasdfasdfa")); } } class Solution { public int lengthOfLongestSubstring(String s) { if(s == null) return 0; int ans = 0; //用来保存不重复子串的左边界 int left = 0; //Map记录了出现过的字符和对应的位置 Map<Character, Integer> map = new HashMap<>(); for(int i = 0;i < s.length();i++){ char ch = s.charAt(i); //判读当前字符是否在之前遍历的过程中出现过 //若出现过,则更新左边界 if(map.containsKey(ch) && map.get(ch) >= left){ left = map.get(ch)+1; } //若没有出现过,则更新结果 else { ans = Math.max(ans, i-left+1); } //跟新出现过的字符 map.put(ch, i); } return ans; } }
用数组记录字符出现的位置(此种方法相比上面的方法在应用范围上有所限制,只能应用ASCII字符集):
该方法可以通过测试说明测试数据是ASCII字符集。
public class Solution { public int lengthOfLongestSubstring(String s) { if(s == null) return 0; int ans = 0; //用来保存不重复子串的左边界 int left = 0; //map记录了出现过的字符和对应的位置 int[] map = new int[260]; Arrays.fill(map, -1); for(int i = 0;i < s.length();i++){ char ch = s.charAt(i); //判读当前字符是否在之前遍历的过程中出现过 //若出现过,则更新左边界 if(map[ch] != -1 && map[ch] >= left){ left = map[ch]+1; } //若没有出现过,则更新结果 else { ans = Math.max(ans, i-left+1); } //跟新出现过的字符 map[ch] = i; } return ans; } }
相关文章推荐
- 单页面Web应用开发框架:Durandal学习入门
- Android版xx助手之天天酷跑外挂详细分析
- OAF知识点整理
- UI控件
- 从武侠小说到程序员面试
- 查看sqlserver被锁的表以及如何解锁
- 记车架号识别程序部署参考文档
- 是否由另一控件传递来的字符?
- ios button超出父视图如何响应事件
- 关于布局设计器的思考
- Quartz 用 cron 表达式存放执行计划
- sql截取字符串SUBSTRING
- Android实现网络多线程文件下载
- 机器学习基础(十二)—— 数学基本理论拾遗
- 讲解Android中的Widget及AppWidget小工具的创建实例
- JSON.parse()方法
- PHP5中Cookie与 Session详解
- Win8系统如何开启环绕立体声效果?
- React 简介
- URL参数带中文的处理