Longest Substring without repeating Characters(12.5)
来源:互联网 发布:能具面具 淘宝 编辑:程序博客网 时间:2024/05/21 21:42
题意:给定一个字符串,找出最长不重复的子串。
思路1:贪心法。从左往右扫描,当遇到重复字母时,以上一个重复字母的index+1,作为新的搜索起始位置,直至最后一个字母。
思路二:滚动数组法。维护一个hashset,两个指针end和start。记录当前遍历的子串,具体见代码。
代码:
package com.LongestSubstring_12_5;import java.util.HashSet;import java.util.Set;public class LongestSubstring { //贪心计算 public int calLength(String s){ //记录字符上次出现过的位置 int[] last = new int [26]; int start = 0;//记录当前子串的起始位置 for (int i = 0; i < last.length; i++) { last[i] = -1; } int max_len = 0; for(int i = 0 ; i < s.length() ; i++){ if(last[s.charAt(i)-'a'] >= start){ max_len = Math.max(max_len, i-start); start = last[s.charAt(i)-'a']+1; } last[s.charAt(i) - 'a'] = i; } return max_len; } //滚动窗口解法 public int calLength2(String s){ int start = 0; int end = 0; int max = 0; HashSet<Character> set = new HashSet<>(); while (end < s.length()) { if(set.contains(s.charAt(end))){ max = Math.max(max, end-start); while (s.charAt(start) != s.charAt(end)) { set.remove(s.charAt(start)); start++; } start++; }else set.add(s.charAt(end)); end++; } max = Math.max(max, end-start); return max;} public static void main(String[] args) { String string = "qpxrjxkltzyx"; LongestSubstring lSubstring = new LongestSubstring(); System.out.println(lSubstring.calLength(string)); System.out.println(lSubstring.calLength2(string)); }}
0 0
- 12.5 Longest Substring without Repeating Characters
- Longest Substring without repeating Characters(12.5)
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Deep Learning方向的paper整理
- java POI导出多张图片到表格(占位符方式)
- redis TTL使用
- 润乾报表v4-jsp中获得报表某一列的数据
- 集成百度地图的常见错误
- Longest Substring without repeating Characters(12.5)
- web.xml配置
- 值转换器IValueConverter
- 1622-5 孔富晨 总结《2016年11月27日》 【连续第58天总结】
- 小白笔记---------------------------leetcode(203. Remove Linked List Elements )
- 利用ffmpeg工具基于nginx-rtmp-module模块搭建HLS
- 英语总结系列(二十三):Baby上海一月游
- 有关使用字节流对任意文件进行加密的办法
- 使用IntelliJ IDEA 13搭建Android集成开发环境(图文教程)