[Rookie Training] Sword Finger Offer 48. The longest substring without repeated characters

Title description:

Please find the longest substring that does not contain repeated characters from the string, and calculate the length of the longest substring.

Example 1:
Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring without repeated characters is "abc", its length is 3.

Example 2:
Input: "bbbbb"
Output: 1
Explanation: Because the longest substring without repeated characters is "b", its length is 1.

Example 3:
Input: "pwwkew"
Output: 3
Explanation: Because the longest substring without repeated characters is "wke", its length is 3.
Please note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.

Tip:
s.length <= 40000

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof
the copyright The collar is owned by the network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving ideas:

Method 1: Violence. At first glance, the simplest solution to this problem is to use a set. Here I first thought of using List to do it, which probably requires two loops, and the time complexity is O(n²) . Because every time I go to a new List, the space complexity is also very high. This method is not recommended.
This method is to traverse each element in the string next to each other to find its largest unique substring. If the next one does not repeat, it will list.add (the element). If it is repeated, it means that this substring is the longest. We need to jump out of the inner loop, and then compare the length of the list with the longest length obtained before and update it.

Method 2: Look at the comment area, there are many solutions using sliding windows and dp. I will think about it first and add it later.

Code:

public class jianzhi_Offer_48 {
    
    
    //暴力
    public int lengthOfLongestSubstring(String s) {
    
    
        if (s.length() == 0){
    
    
            return 0;
        }
        int maxnum = 1;
        for (int i = 0; i < s.length(); i++) {
    
    
            ArrayList list = new ArrayList();
            for (int j = i; j < s.length(); j++) {
    
    
                if (list.contains(s.charAt(j)) == false) {
    
    
                    list.add(s.charAt(j));
                }
                else {
    
    
                    break;
                }
            }
            maxnum = Math.max(maxnum,list.size());
        }
        return maxnum;
    }

    public static void main(String[] args) {
    
    
        jianzhi_Offer_48 obj = new jianzhi_Offer_48();
        System.out.println(obj.lengthOfLongestSubstring("au"));

    }
}

Guess you like

Origin blog.csdn.net/Puppet__/article/details/115164325