leetcode 3. Longest Substring Without Repeating Characters

转载 2016年05月31日 09:31:28

题目

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

思路:利用一个exist数组保存字符是否出现(假设char set是ascii),从前向后遍历数组,如果遇到已存在的字符,应该回退到这个字符上次出现的下一个位置从新开始统计,同时注意exist数组的同步更新。

代码

public class Solution {
   public int lengthOfLongestSubstring(String s) {
    	if(s.equals("")){
    		return 0;
    	}
    	int res = 1;
    	int start = 0;
    	boolean exist[] = new boolean[128];
    	for(int i = 0;i < 128; i++){
    		exist[i] = false;
    	}
    	for(int i = 0;i < s.length(); i++){
    		char c = s.charAt(i);
    		if(exist[c]){
    			for(int k = start;k < i; k++){
    				if(s.charAt(k)==c){
    					start = k+1;
    					break;
    				}
    				exist[s.charAt(k)] = false;
    			}
    		}else{
    			exist[c] = true;
    		}
    		if((i-start+1) > res){
    			res = i - start + 1;
    		}
    	}
    	
    	return res;
    }
}

相关文章推荐

[LeetCode - 滑动窗口] 3. Longest Substring Without Repeating Characters

1 问题 Given a string, find the length of the longest substring without repeating characters. Exa...

LeetCode | 3. Longest Substring Without Repeating Characters

leetcode.com 3. Longest Substring Without Repeating Characters

LeetCode- 3. Longest Substring Without Repeating Characters

Description Given a string, find the length of the longest substring without repeating characters.E...

leetcode_3 - Longest Substring Without Repeating Characters

leetcode_3 : Longest Substring Without Repeating Characters标签(空格分隔): leetcode string twoPoints setGi...

LeetCode(3)--Longest Substring Without Repeating Characters

题目如下: Given a string, find the length of the longest substring without repeating characters. For ex...

LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希)

LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希) 1. 从左到右扫描字符串,读入每一位字符。当该位字符上一次出现...

【leetcode】【3】Longest Substring Without Repeating Characters

一、问题描述 Given a string, find the length of the longest substring without repeating characters. For e...

LeetCode#3. Longest Substring Without Repeating Characters

求最长子串(子串中没有重复元素)

LeetCode3. Longest Substring Without Repeating Characters(最长不重复子串)

题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/ Given a ...

leetcode 3 -- Longest Substring Without Repeating Characters

leetcode 3 – Longest Substring Without Repeating Characters 题目: Given a string, find the lengt...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)