leetcode【3】longest substring without repeating characters

版权声明:本文为博主原创文章,未经允许,不得转载,如需转载请注明出处 https://blog.csdn.net/ssjdoudou/article/details/83276624

写在最前面:机器学习也要搞,leetcode也要刷,为了方便大家调试,给的代码都是添加了测试代码的,直接运行即可

题目如下:

Leetcode/1/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.

给定一个字符串s,找出不含有重复字符的最长子串的长度

首先是暴力法:基本思路是通过ifallUnique函数查找该字符串是否包含重复字符,是的话返回false,否则的话将新的字符加进去,因为给的是一个字符串,将字符串挨个转成Character类型,然后两层循环遍历,通过ans记录已经存在的最长字符串,max函数比较下一组不包含重复字符的字符串的长度

package Arithmetic;

import java.util.HashSet;
import java.util.Set;

public class lengthOfLongestSubstring {                                                //暴力法

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String k = "abcabcbbdsgfedshgdrsfgdsfgssssdgewrqwerqewrsadfdsafdsafafddsafdsafdsafrwqer";
        lengthOfLongestSubstring l = new lengthOfLongestSubstring();
        System.out.println(l.lengthOfLongestSubstring(k));
    }
    public int lengthOfLongestSubstring(String s) {
        int ans = 0;
        for(int i=0;i<s.length();i++)
            for(int j=i+1;j<=s.length();j++) 
                if (ifallUnique(s,i,j)) 
                    ans = Math.max(ans, j - i);
        return ans;
        
    }
    
    public boolean ifallUnique(String s, int start, int end) {                        //判断是否唯一
        Set<Character> set = new HashSet<>();
        for (int i = start; i < end; i++) {
            Character ch = s.charAt(i);
            if (set.contains(ch)) 
                return false;
            set.add(ch);
        }
        return true;
    }
}


上面一个我讲的很细了,也很好理解,然后讲一讲时间复杂度小一点的
假设给定子串s[i,j],还是添加字符

若重复:记录此时滑动窗口大小,并与最大滑动窗口比较,赋值。然后滑动窗口大小重定义为1,右移一个单位。

若不重复:滑动窗口头不变,结尾+1,整个窗口加大1个单位,继续比较下一个。

package Arithmetic;

import java.util.HashSet;
import java.util.Set;

public class lengthOfLongestSubstring2 {

    public static void main(String[] args) {
        String k = "2314fdssafewqroiqwue4riu2qjrkewhfu1y243985yrejhfskjdsahgfasjdhf98q2wy9rhewqkfhdsafhjdsahgfuasdrhdkjsh8327484y3(*^(*^%#$&^%#";
        // TODO Auto-generated method stub
        lengthOfLongestSubstring2(k);
        
    }
     public static int lengthOfLongestSubstring2(String s) {                
         
            int n = s.length();
            Set<Character> set = new HashSet<>();
            int ans = 0, i = 0, j = 0;
            while (i < n && j < n) {
                // try to extend the range [i, j]
                if (!set.contains(s.charAt(j))){
                    set.add(s.charAt(j++));
                    ans = Math.max(ans, j - i);
                }
                else {
                    set.remove(s.charAt(i++));
                }
            }
            System.out.println(ans);
            return ans;
        }
}


你以为到这里就结束了,不!下面上python3的,以下代码也可以直接运行

class lengthOfLongestSubstring:

    def lengthOfLongestSubstring(self, s):
        start = 0
        maxlength = 0
        substring = {}                          # 定义子串,此处的{}是一个字典,可存储任意对象
        for i, j in enumerate(s):
            if j in substring and start <= substring[j]:  # 如果在子串里
                start = substring[j] + 1                  # 窗口向后滑动一个
            else:
                maxlength = max(maxlength, i - start + 1)
            substring[j] = i
        print(maxlength)
        return maxlength


if __name__ == '__main__':
    xxx = lengthOfLongestSubstring()
    xxx.lengthOfLongestSubstring('3sssfsdfsrdsfsdvcbxndfewrewfsfadsfaewrwrewrewrs')

    初始化了一个实例,enumerates函数是用来遍历序列中的元素以及它们的下标

猜你喜欢

转载自blog.csdn.net/ssjdoudou/article/details/83276624