Leetcode 詳解(Substing without repeats character)

來源:互聯網
上載者:User

標籤:

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.

我自己的代碼:

public class Solution {    public int lengthOfLongestSubstring(String s) {        int slenmax=0;        for(int i=0;i<s.length();i++)        {            int j=i+1;            boolean flag=true;            while(j<s.length()&&flag)            {                for(int k=i;k<j;k++)                {                                      if(s.charAt(j)==s.charAt(k))                   {                       flag=false;                       j--;                   }                }                j++;            }            int slen=j-i;            if(slen>slenmax)                slenmax=slen;        }        return slenmax;    }}

運行時可以通過,但是在提交時出現逾時(思路比較簡單,因而時間複雜度相應會比較高)

clean Code:

public class Solution {    public int lengthOfLongestSubstring(String s) {        boolean[] exist = new boolean[256];             //用表格處理,尋找時會很快        int i = 0, maxLen = 0;        for (int j = 0; j < s.length(); j++) {            while (exist[s.charAt(j)]) {                //這個while是精髓                exist[s.charAt(i)] = false;                i++;            }            exist[s.charAt(j)] = true;            maxLen = Math.max(j - i + 1, maxLen);        }        return maxLen;    }} 

 註:借用了表的形式,把字串中的字母依次存入表中並進行相應標記(如 exist[s.charAt(i)] = false;)。解決思路是:設定兩個指標(i, j),都放在左頭開始,從左至右,遇到有兩個相同字母的情況,則計算兩相同字母間距,更新最大間距,並且把i 也放在j 處,再進行計算最大間距。 

 

Leetcode 詳解(Substing without repeats character)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.