首页 > 其他 > 详细

leetcode 3. Longest Substring Without Repeating Characters

时间:2019-04-17 23:48:06      阅读:129      评论:0      收藏:0      [点我收藏+]

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;
    }
}

leetcode 3. Longest Substring Without Repeating Characters

原文:https://www.cnblogs.com/exhausttolive/p/10726974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!