Leetcode Two Sum (java)Longest Substring Without Repeating Characters,leetcoderepeating

來源:互聯網
上載者:User

Leetcode Two Sum (java)Longest Substring Without Repeating Characters,leetcoderepeating

解法一:

class Solution {    public int lengthOfLongestSubstring(String s) {        int max = 0;        if (s.length() <= 1) {            max = s.length();            return max;        }        for (int i = 0; i < s.length(); i++) {            //建立一個StringBuilder儲存臨時字串            StringBuilder str = new StringBuilder();            str.append(String.valueOf(s.charAt(i)));            //判斷每個字串多長            for (int j = i + 1; j < s.length(); j++) {                //當出現相同字串則停止匹配跳出                if (str.indexOf(String.valueOf(s.charAt(j))) == -1) {                    str.append(String.valueOf(s.charAt(j)));                }                else{                    break;                }            }            //記錄最大長度            if (str.length() > max) {                max = str.length();            }        }        return max;    }}

 這種解法使用的是Brute Force演算法,即是暴力搜尋匹配,時間複雜度較高

 

解法二:

class Solution {    public int lengthOfLongestSubstring(String s) {        int max = 0;        //儲存每個字元出現的位置        Hashtable<Character, Integer> map = new Hashtable<Character, Integer>();        //遍曆字串        for (int i = 0, j = 0; i < s.length(); i++) {            //當出現相同字元時改變視窗左邊框位置並記錄視窗長度            if (map.containsKey(s.charAt(i))) {                j = Math.max(map.get(s.charAt(i)) + 1 , j);            }            max = Math.max(max, i - j + 1);            map.put(s.charAt(i), i);        }        return max;    }}

 這種解法的思想是計算兩個相同的字元之間的長度,好比作一個視窗在字串上右邊框向右展開,若右邊框碰到視窗內已存在的字元,那麼左邊框向右展開到到視窗已存在字元的右邊,時間複雜度較低


github地址:https://github.com/CyanChan/leetcode

聯繫我們

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