前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode——Longest Substring Without Repeating Characters

LeetCode——Longest Substring Without Repeating Characters

作者头像
felixzhao
发布2019-02-13 09:53:52
3220
发布2019-02-13 09:53:52
举报
文章被收录于专栏:null的专栏

题目:

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.

解题过程:

1、分析

   题目中主要是要统计子串的长度,这样的子串要满足一个条件就是子串中没有重复的元素。要实现快速的查找,比较方便的是使用Hash表的结构。

2、思路

   在查找到相同字符的时候要删除掉相同字符前面的所有字符。所以要做好子串的第一个字符的下标的保存。

程序代码:

代码语言:javascript
复制
public static int lengthOfLongestSubstring(String s) {
		//利用hash表
		HashMap<Character, Integer> map = new HashMap<Character, Integer>();
		int length = map.size();
		int lenTmp = map.size();
		char c[] = s.toCharArray();// 将字符串转换为字符数组
		int start = 0;
		
		for (int i = 0; i < c.length; i++) {
			if (map.containsKey(c[i])) {
				int j = start;
				while (c[j] != c[i]){
					map.remove(c[j]);
					j++;
				}
				map.remove(c[j]);
				start = j+1;
				map.put(c[i], i);
			} else {
				map.put(c[i], i);
			}
			lenTmp = map.size();
			length = (length < lenTmp) ? lenTmp : length;
		}
		return length;
	}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年01月15日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:
  • 解题过程:
    • 1、分析
      • 2、思路
      • 程序代码:
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档