leetcode 3. Longest Substring Without Repeating Characters

My solution

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] c = new int[256];
        int j = 0;
        int longest = 0;
        for (int i = 0; i < s.length(); ++i) {
            int idx = (int)(s.charAt(i) - '\0');
            if (c[idx] == 0) {
                c[idx] += 1;
                longest = Math.max(longest, i - j + 1);
            }
            else {
                for (;(int)(s.charAt(j) - '\0') != idx; ++j) {
                    c[(int)(s.charAt(j) - '\0')] -= 1;
                }
                j += 1;
            }
        }
        return longest;
    }
}

It's not so elegant.And the more elegant method

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] c = new int[256];
        int i= 0, j = 0;
        int longest = 0, N = s.length();
        while (i < N && j < N) {
            int a = (int)(s.charAt(i) - '\0');
            if (c[a] == 0) {
                c[a] += 1;
                ++i;
                longest = Math.max(longest, i - j);
            }
            else {
                int b = (int)(s.charAt(j) - '\0');
                c[b] -= 1;
                ++j;
            }
        }
        return longest;
    }
}
posted on 2019-04-17 23:19  王 帅  阅读(109)  评论(0编辑  收藏  举报