zoukankan      html  css  js  c++  java
  • Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    解题思路:
    首先定义两个整形变量p,q用来保存子串的下标,p表示子串的首字母下标,q表示子串的尾字母下标。子串A(p,q)需要满足性质:不含有重复的字母。
    每经过一次循环,q往后移动一位即q+1;p的值是否变化取决于下标q所指向的那个元素是否和子串的元素重复,如果不重复,那么p值不变;如果有重复,比如子串中有下标为k的元素与之重复,那么为了维护子串的性质,需要将p值修改为k+1,使得子串A(p,q)维护的元素不重复的性质。变量max表示循环后的最大子串长度。算法的时间代价:O(n)
    相关代码如下:
     
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s==null || s.equals("")){
                return 0;
            }
            int p=0,q=0;    //p,q用于保存子串的下标
            int max = 1;    //max用于保存子串的最大长度
            for(int i=1;i<s.length();i++){
                char ch = s.charAt(i);
                q = q+1;
                for(int j=p;j<i;j++){
                    if(ch == s.charAt(j)){
                        p = j+1;
                        break;
                    }
                }
                max = (q-p+1)>max?(q-p+1):max;
            }
            return max;
        }
    }
  • 相关阅读:
    Linux安装RocketMQ
    初识SpringMVC
    事物的锁机制和七种传播行为
    Spring事物
    JdbcTemplate模板
    注解
    AOP代理工厂方式实现增强
    面试题
    Spring框架静态代理和动态代理
    Bootstrap框架(基础篇)之按钮,网格,导航栏,下拉菜单
  • 原文地址:https://www.cnblogs.com/ming-zi/p/6084504.html
Copyright © 2011-2022 走看看