码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Substring Without Repeating Characters

时间:2014-11-19 01:35:20      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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.

算法:用map判断字符是不是出现过

java:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if(len<=1){
            return len;
        }
        int[] map=new int[256];
        int maxLen=-1;
        int sum=0;
        int i=0;
        while(i<len){
            //第一次出现
            if(map[s.charAt(i)]==0){
                sum++;
                //存储第一次出现的下标+1(如果存储i的话,下标为0的元素也可能重复,所以存储i+1)
                map[s.charAt(i)]=i+1;
                i++;
            }else{
                if(sum>maxLen){
                    maxLen=sum;
                }
                int start=map[s.charAt(i)];
                sum=i-start+1;
                Arrays.fill(map,0);
                i=start;
                sum=0;
            }
        }
        if(sum>maxLen){
            maxLen=sum;
        }
        return maxLen;
    }
}

c++:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int a[256];
        memset(a,0,256*4);
        int i=0;
        int sum=0;
        int max=0;
        while(i<s.length()){
            if(a[(int)s[i]]==0){
                a[(int)s[i]]=i+1;
                sum++;
                if(sum>max){
                    max=sum;
                }
                i++;
            }else{
                i=a[(int)s[i]];
                memset(a,0,256*4);
                sum=0;
            }
        }
        if(sum>max){
            max=sum;
        }
        return max;
    }
};











Longest Substring Without Repeating Characters

标签:leetcode

原文地址:http://blog.csdn.net/u010786672/article/details/41252901

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!