leetcode 3 Longest Substring Without Repeating Characters

題目詳情

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

題目要求輸入一個字符串,咱們要找出其中不含重複字符的最長子字符串,返回這個最長子字符串的長度。code

Examples:
輸入"abcabcbb",最長不含重複字符子字符串"abc",返回3.
輸入"bbbbb",最長不含重複字符子字符串"b",返回1.
輸入"pwwkew",最長不含重複字符子字符串"wke",返回3.字符串

想法

  • 這道題的思路也比較簡單,首先聲明一個max變量存儲結果,聲明一個temp字符串暫存當前的不重複字符串。
  • 對於字符串中的每個字符c,先判斷temp中是否已經存在這個字符,若是不存在,直接將c添加到temp,若是已存在,則新的temp字符串就從不含前一個c字符的地方開始。
  • 每次截取字符串以前都判斷一下長度是否比max大。

解法

public int lengthOfLongestSubstring(String s) {
        int max = 0;
        String temp = "";
        
        for(char c : s.toCharArray()){
            int index = temp.indexOf(c);
            if(index < 0) temp += c;
            else{
                max = (temp.length() > max) ? temp.length() : max ;
                temp = temp.substring(index+1);
                temp += c;
            }
        }
        max = (temp.length() > max) ? temp.length() : max;
        return max;
    }
相關文章
相關標籤/搜索