[leetcode] Longest Substring Without Repeating Characters

來源:互聯網
上載者:User

標籤:class   blog   code   java   http   tar   

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/

 

思路:利用一個exist數組儲存字元是否出現(假設char set是ascii),從前向後遍曆數組,如果遇到已存在的字元,應該回退到這個字元上次出現的下一個位置從新開始統計(如),同時注意exist數組的同步更新。

 

public class Solution {    public int lengthOfLongestSubstring(String s) {        if (s == null || s.length() == 0)            return 0;        int res = 1;        boolean[] exist = new boolean[256];        int start = 0;        for (int i = 0; i < s.length(); i++) {            char ch = s.charAt(i);            if (exist[ch]) {                res = Math.max(res, i - start);                for (int k = start; k < i; k++) {                    if (s.charAt(k) == ch) {                        start = k + 1;                        break;                    }                    exist[s.charAt(k)] = false;                }            } else                exist[ch] = true;        }        res = Math.max(res, s.length() - start);        return res;    }    public static void main(String[] args) {        System.out.println(new Solution().lengthOfLongestSubstring("abcabcbb"));        System.out.println(new Solution().lengthOfLongestSubstring("bbbbb"));        System.out.println(new Solution()                .lengthOfLongestSubstring("fpdcztbudxfipowpnamsrfgexjlbjrfoglthewbhtiriznzmolehqnlpwxrfowwwjrd"));    }}

 

 

 

參考:

http://blog.csdn.net/likecool21/article/details/10858799

http://www.programcreek.com/2013/02/leetcode-longest-substring-without-repeating-characters-java/

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.