您的位置:首页 > 其它

3. Longest Substring Without Repeating Characters

2016-03-10 14:36 393 查看
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.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int max = 0, i =0 , j = 0,index;
        int[] hm = new int[128];    //ASCII字符表128个,用来表示某字符当前位置
        while(j<s.length()){     //进行一一遍历
            if(hm[s.charAt(j)] == 0){     //如果没有出现过
                hm[s.charAt(j)] = j+1;        //标记为当前位置
                j++;
                if((j-i) > max)     //j-i为此次寻找的字符串的长度,取最大值
                    max = j-i;
            }
            else {                           //如果出现过
                index = hm[s.charAt(j)];    //index为当前位置
                hm[s.charAt(j)] = 0;
                if (i < index)
                    i = index;
            }
        }
        return max;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: