Leetcode[3] Longest Substring Without Repeating Characters

来源:互联网 发布:北京11选5遗漏数据查询 编辑:程序博客网 时间:2024/06/08 16:54

Given astring, 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.

C++版

class Solution {public:int lengthOfLongestSubstring(string s){    int n = s.length();    int i=0,j=0;  ///两个指针,i始终指向新的字串开头,j一直往后走.    int maxLen = 0;    bool exist[256] = {false};    for(;j <n ; j++) {        if (exist[s[j]]) {            maxLen = max(maxLen, j-i);            while (s[i] != s[j]) {                exist[s[i]] = false;                i++;            }           i++;        } else {            exist[s[j]] = true;        }    }    return max(maxLen, j-i);}};
Java版

public class Solution {    public int lengthOfLongestSubstring(String s) {        boolean[] exist = new boolean[256];        int i = 0, j = 0, maxLen = 0;        for (; j < s.length(); j++) {            while (exist[s.charAt(j)]) {                exist[s.charAt(i)] = false;                i++;            }            exist[s.charAt(j)] = true;            maxLen = Math.max(j - i + 1, maxLen);        }        return maxLen;    }}



0 0
原创粉丝点击