美文网首页
最长不重复子串

最长不重复子串

作者: yutz | 来源:发表于2019-02-10 14:16 被阅读0次

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

Example 1:

Input: "abcabcbb"Output: 3Explanation:The answer is"abc", with the length of 3.

Example 2:

Input: "bbbbb"Output: 1Explanation: The answer is"b", with the length of 1.

Example 3:

Input: "pwwkew"Output: 3Explanation: The answer is"wke", with the length of 3. Note that the answer must be asubstring,"pwke"is asubsequenceand not a substring.

普通解法:遍历,循环,begin为字符串开头起始位置,[begin,i)之间的字符串是不重复的子串,内层循环判断i位置的字符是否与这个区间上的某个字符相等


class Solution {

    public int lengthOfLongestSubstring(String s) {

        int begin=0;

        int len=0;

        if(s.length()>0)

            len=1;

        for(int i=0;i<s.length(); i++)

        {

            for(int j=begin;j<i;j++)

            {

                if(s.charAt(i)==s.charAt(j))

                {

                    if(i-begin>len)

                        len=i-begin;

                    begin=j+1;

                    break;

                }

                else if(j==i-1)

                {

                    if(i-begin+1>len)

                        len=i-begin+1;

                }

            }

        }

        return len;

    }

}

哈希表解法:利用hashmap的<key,value>结构存储字符,value即为字符的位置

   public int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }

相关文章

  • 【leetcode3】 3. Longest Substrin

    关键字:最长不重复子串、双指针 难度:Medium 题目大意:求一个字符串最长不重复子串的长度 题目: Given...

  • LeetCode #1044 Longest Duplicate

    1044 Longest Duplicate Substring 最长重复子串 Description:Given...

  • 3、Longest SubString Without Repe

    Examples:找出最长无重复子串长度Given "abcabcbb", the answer is "abc"...

  • iOS面试题汇总---算法类

    字符串 【3】最长回文子串 【3】最长无重复子串 【1*】字符串转数字 【4】KMP 算法 【2】字符串全排列 【...

  • 最长不重复子串

    1. 问题定义 最长不重复子串:一个字符串中最长的没有重复字符的子串。举个? : abcabcbb 最长子串 a...

  • 寻找最长重复子串,后缀数组的方法

    寻找最长重复子串,如ask not what your country can do for you ,but w...

  • 文章收藏

    iOS面试题系列之常见算法 排序算法整理 字符串【3】最长回文子串【3】最长无重复子串【1*】字符串转数字【4】K...

  • 3、Longest Substring Without Repe

    题设 要点 双指针维护最长重复子串的位置 动态规划 寻找字符串的最长子串,就是要维护一个区间[left , rig...

  • 无重复字符串的最长子串

    题目大意:给定一个字符串,找出不含有重复字符的最长子串的长度 解读: 1、给定abcabcbb,没有重复子串的最长...

  • 最长重复子串

    前言 据统计,在所有程序中,关于字符串处理的程序占到了百分之八十以上,所以关于字符串处理的算法十分多,而且关于数字...

网友评论

      本文标题:最长不重复子串

      本文链接:https://www.haomeiwen.com/subject/apbteqtx.html