LeetCode-Longest Substring Without Repeating Characters<ERROR>

本文探讨如何在给定字符串中找到最长的无重复字符子串,通过Trie树法和后缀数组方法实现解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:disappearedgod
时间:2014-8-25

题目

Longest Substring Without Repeating Characters

  Total Accepted: 20666  Total Submissions: 92944 My Submissions

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.


想法
举一个例子“abcabcabcd”

第一种方法 Trie树法
将String的后缀序列输入Trie树。
public class Solution {
    private TrieST trie;
    public int lengthOfLongestSubstring(String s) {
        int res = 0;
        int tmp = 0;
        HashSet<Integer> set = new HashSet<Integer>();
        if(s.length() == 0)
            return 0;
        trie = new TrieST();
        for(int i = 0; i < s.length(); i++){
            trie.put(s.substring(i));
            tmp = set.get(trie.get(s.substring(i)));
            res = res > tmp ? res : tmp;
        }
        return res;  
    }
    public class TrieST{
        private Node root;
        private int R = 256;
        private class Node{
            private int val;
            private Node[] next = new Node[R];
        }
        public int get(String key){
            Node x = get(root, key, 0);
            if(x == null)
                return null;
            return x.val;
        }
        private int get(Node x, String key, int d){
            if(x == null) return null;
            if(d == key.length()) return x;
            char c = key.charAt(d);
            return get(x.next[c], key, d+1);
        }
        
        public void put(String key, int val){
            root = put(root, key, val, 0);
        }
        
        private Node put(Node x, String key, int val, int d){
            if(x == null) return null;
            if(d == key.length()){
                x.val = val;
                return x;
            }
            char c = key.charAt(d);
            x.next[c] = put(x.next[c], key, val, d+1);
        }
    }
   
}

暴力法后缀数组
想用一下JAVAAPI解决一下后缀数组题,用list和Collection排序。
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        ArrayList<String> a = new ArrayList<String>();
        for(int i = 0; i < s.length(); i++)
            a.add(s.substring(i));
        Collections.sort(a);
        int max = 0;
        String ret = "";
        for(int i = 1; i < s.length(); i++){
            if(max < a.get(i).compareTo(a.get(i-1))){
                max =a.get(i).compareTo(a.get(i-1));
                ret = a.get(i-1);
            }
        }
        return max;
    }
}


结果

结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值