LeetCode (3): no repetitive characters longest substring

Casual working

ex

Solving

  • The casual working described, to determine the length of the longest character string without duplication, we can use a queue;
    added sequentially to the characters in the queue, if the presence of the team, and vice versa, a team (until removal of repeated characters)
class Solution {
	public int lengthOfLongestSubstring(String s) {
		if(s.trim().isEmpty()&&(!s.isEmpty()))return 1;
		if(s.isEmpty())return 0;
		Queue<Character> q = new LinkedList<Character>();
		int maxLength=1,length=1;
		q.add(s.charAt(0));
		
		for(int i=1;i<s.length();i++) {
			if(q.contains(s.charAt(i))) {
				while(!q.element().equals(s.charAt(i))) {
					q.remove();
					length--;
				}
				q.remove();
				length--;
			}
			q.add(s.charAt(i));
			length++;
			if(length>maxLength) {
				maxLength=length;
			}
		}
		
		return maxLength;
		
	}
}

result

Official explanations

  • To traverse all possible substring given string s and call the function allUnique. If it turns out the return value is true, we will update the character substring no duplicate answers maximum length.
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int ans = 0;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j <= n; j++)
                if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
        return ans;
    }

    public boolean allUnique(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;
    }
}

Published 40 original articles · won praise 12 · views 5698

Guess you like

Origin blog.csdn.net/weixin_43488958/article/details/104690206