• 剑指offer 48 -最长不含重复字符的子字符串 动态规划


    package jianzhioffer;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class test48 {
        public static void main(String[] args) {
            String s="pwwkew";
            System.out.println(lengthOfLongestSubstring(s));
        }
        public static int lengthOfLongestSubstring(String s) {
           //优化
            if(s==null||s.length()==0){
                return 0;
            }
            //用动态规划dp[j]表示j位置结尾的最长子字符串长度
            //i位置表示最近的和j重复的字母位置,也就是s[i]=s[j]
            //i=-1,表示前面没有重复的,dp[j]=dp[j-1]+1;
            //dp[j-1]<j-i,,i在j-1外面,dp[j]=dp[j-1]+1
            //dp[j-i]>=j-i说明字符 s[i]s[i] 在子字符串 dp[j-1]dp[j−1] 区间之中 ,则 dp[j]dp[j] 的左边界由 s[i]s[i] 决定,
            //即 dp[j] = j - i ,比如pwwd,第二个w时候
    
               
            Map<Character, Integer> dic = new HashMap<>();
            int res = 0, tmp = 0;
            for(int j = 0; j < s.length(); j++) {
                int i = dic.getOrDefault(s.charAt(j), -1); // 获取索引 i
                dic.put(s.charAt(j), j); // 更新哈希表
                tmp = tmp < j - i ? tmp + 1 : j - i; // dp[j - 1] -> dp[j]
                res = Math.max(res, tmp); // max(dp[j - 1], dp[j])
            }
            return res;
    
                
         
    
    
           
            //笨方法
            // int max=0;
            // for(int i=0;i<s.length();i++){
            //     int x=helper(i,s,new ArrayList<Character>());
            //     if(max<x){
            //         max=x;
            //     }
            //     if(max==s.length()){
            //         return max;
            //     }
            //     if(max>=(s.length()-i+1)){
            //         return max;
            //     }
            // }
            // return max;
            
        }
        // public static int helper(int start,String s,List<Character> temp){
        //     for(int i=start;i<s.length();i++){
        //         char x=s.charAt(i);
        //         if(temp.size()==0){
        //             temp.add(x);
        //         }else if(!temp.contains(x)){
        //             temp.add(x);
        //         }else{
        //             return temp.size();
        //         }
        //     }
        //     return temp.size();
    
        // }
        
    }
  • 相关阅读:
    java 变量常量作用域
    简述Integer
    简述(非)静态代码块和构造方法的执行顺序
    父类子类在有(无)参构造方法继承的一些规则
    equals和==的区别
    创建和调用自定义类的方法简述
    int变量与double变量混合运算时的常见问题及方法
    int变量运算过程中的常见问题及方法
    初始Java
    Eclipse常用快捷键
  • 原文地址:https://www.cnblogs.com/jieyi/p/14309887.html
Copyright © 2020-2023  润新知