[LeetCode]Q3. Longest Substring Without Repeating Characters

Problem Description

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.
[https://leetcode.com/problems/longest-substring-without-repeating-characters/]

思路

把词库里所有的字母都遍历一遍,在字符串中算出每个字符与前一个相同字符的距离。之后利用这个距离数组,计算最长无重复字符字符串。

代码

package Q3;

public class Solution {
    public static int lengthOfLongestSubstring(String s) {
        if (s.length() < 1)
            return 0;
        return GetMaxLen(FindLen(s));

    }

    public static int GetMaxLen(int[] SameLen) {
        int max = 0;
        int newMax = 0;
        for (int i = 0; i < SameLen.length; i++) {
            if (SameLen[i] == 0)
                newMax++;
            else if (SameLen[i] < newMax)
                newMax = SameLen[i];
            else if (SameLen[i] > newMax)
                newMax++;
            if (newMax > max)
                max = newMax;

        }

        return max;
    }

    public static int[] FindLen(String s) {
        int SameLen[] = new int[s.length()];
        for (int i = 0; i < SameLen.length; i++) {
            SameLen[i] = 0;
        }
        String tmp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ";
        System.out.print(tmp.length());
        for (int i = 0; i < tmp.length(); i++) {
            char a = tmp.charAt(i);
            int k = 1;
            int first = 1;
            for (int j = 0; j < s.length(); j++) {
                if (s.charAt(j) == a && first == 1) {
                    SameLen[j] = 0;
                    k = 1;
                    first = 0;
                } else {
                    if (s.charAt(j) == a) {
                        SameLen[j] = k;
                        k = 1;
                    } else {
                        k++;
                    }
                }
            }
        }

        return SameLen;
    }

    public static void main(String[] args) {

        System.out.print(lengthOfLongestSubstring("asd"));

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值