LeetCode(3):なし、繰り返し文字の最長部分文字列

カジュアルワーキング

EX

解決

  • カジュアルな作業が重複することなく最長の文字列の長さを決定するために、説明し、我々はキューを使用することができます。
    キュー内の文字を順に加え、チームの存在あれば、その逆も同様、(繰り返される文字の除去まで)チーム
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;
		
	}
}

結果

公式の説明

  • 文字列s与えられたすべての可能な部分文字列を横断し、機能allUniqueを呼び出します。それは戻り値がtrueで判明した場合、我々は重複解答の最大長をサブストリングない文字を更新します。
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;
    }
}

公開された40元の記事 ウォン称賛12 ビュー5698

おすすめ

転載: blog.csdn.net/weixin_43488958/article/details/104690206