LeetCode 3 Longest Substring Without Repeating Characters

來源:互聯網
上載者:User

標籤:leetcode   python   c   c++   java   

Problem: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.
Solution:無題目大意:題意比較簡單,給定一個字串,要求得出最長子串的長度,子串要求無重複字元。解題思路:可以採用Hash儲存+動態規劃的方式解決,從左至右遍曆一遍,標記子串的最左邊位置,當遇到重複字元時,說明當前子串已經結束,開始一個新的字串,更新字元的位置和子串的left。Java原始碼:
public class Solution {    public int lengthOfLongestSubstring(String s) {        int left=0,Max=0;        Map<Character,Integer> map = new HashMap<Character,Integer>();        char[] chs = s.toCharArray();        for(int i=0;i<chs.length;i++){            if(map.containsKey(chs[i]) && map.get(chs[i])>=left){                left = map.get(chs[i])+1;            }            map.put(chs[i],i);            Max = Max>(i-left+1)?Max:(i-left+1);        }        return Max;    }}
C語言原始碼:
#include<limits.h>#include<stdio.h>int lengthOfLongestSubstring(char* s) {    int i,j,left=0,Max=0,hash[256];    for(j=0;j<256;j++)hash[j]=INT_MAX;    for(i=0;s[i];i++){        if(hash[s[i]]!=INT_MAX && hash[s[i]]>=left)            left=hash[s[i]]+1;        hash[s[i]]=i;        Max = Max>(i-left+1)?Max:(i-left+1);    }    return Max;}

C++原始碼:
class Solution {public:    int lengthOfLongestSubstring(string s) {        int Max=0,left=0;        map<int,int> map;        for(int i=0;i<s.size();i++){            std::map<int,int>::iterator iter=map.find(s[i]);            if(iter!=map.end() && iter->second >=left){                left=iter->second+1;            }            map[s[i]]=i;            Max = Max>(i-left+1)?Max:(i-left+1);        }        return Max;    }};
Python原始碼:
class Solution:    # @param {string} s    # @return {integer}    def lengthOfLongestSubstring(self, s):        left=0        Max=0        hash={}        for i in range(len(s)):            ch = s[i]            if hash.has_key(ch) and hash[ch]>=left:                left=hash[ch]+1            hash[ch]=i            Max= Max if Max>i-left+1 else i-left+1        return Max




LeetCode 3 Longest Substring Without Repeating Characters

聯繫我們

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