leetcode-3

leetcode-3

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

Example 1:

Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:

Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:

Input: “pwwkew”
Output: 3
Explanation: 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.*/

class Solution3 {
    public static int lengthOfLongestSubstring(String s) {
        LinkedList<Character> list = new LinkedList<>();
        int max = list.size(); // 初始化无重复字符串最大长度
        char[] c = s.toCharArray();
        
        for (int i = 0; i < c.length; i++) {
            if (list.contains(c[i])) { // 如果要添加的字符已存在
                boolean flag = true;
                while (flag) { // 循环 直到删除的字符 = 重复的字符
                    char res = list.pop(); 
                    if (res == c[i]) {
                        flag = false;
                    }
                }
            } 
            list.addLast(c[i]); // 添加当前字符到list中,构成最新字符串
            if (list.size() > max) { // 更新最大长度
                max = list.size();
            }
        }
        return max;
    }

	
	public static void main(String  args[]) {
		String s="pwwkew";
		
		  int r=Solution3.lengthOfLongestSubstring(s);
		  System.out.print(r);
		 
		
		
	}
}

发布了34 篇原创文章 · 获赞 4 · 访问量 1456

猜你喜欢

转载自blog.csdn.net/zj20165149/article/details/103899085