LeetCode题解(3)--Longest Substring Without Repeating Characters

来源:互联网 发布:cn域名好不好 编辑:程序博客网 时间:2024/06/06 04:04

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

example

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.

解题思路

采用动态规划:
假设L[i] = s[m…i]是以s[i]结尾的最长不重复子串,维护一个<character,index>的hashmap来存储这些数据,考虑s[i+1]:
如果s[i+1]不在hashmap中,则L[i+1] = s[m…i+1]
如果s[i+1]已经在hashmap中,更新起始字符,假设s[i+1]在hashmap中的 value值为k,
则让起始值m1 = max(m,k) + 1,L[i+1] = s[m1…i+1],同时更新s[i+1]在hashmap中的值为最新值。
因为都是字符,所以可以考虑用数组来代替hashmap。

解题代码

C++

#include <iostream>#include <vector>using namespace std;class Solution {public:    int lengthOfLongestSubstring(string s) {        int maxlen = 0;        int start = 0;        vector<int> hash(256,-1);        for (int i = 0; i < s.length(); i++) {            if(hash[s[i]] >= start)                start = hash[s[i]] + 1;            maxlen = max(i - start + 1, maxlen);            hash[s[i]] = i;        }        return maxlen;    }};int main(){    string s;    cin>>s;    Solution solution;    int re = solution.lengthOfLongestSubstring(s);    cout<<re<<endl;    return 0;}

Java

package leetcode;import java.util.HashMap;import java.util.Map;import java.util.Scanner;public class Solution {    public static int lengtnhOfLongestSubstring(String s) {        int maxlen = 0;        int start = 0;        Map<Character, Integer> map = new HashMap<Character, Integer>();        for (int i = 0; i< s.length(); i++) {            if(map.containsKey(s.charAt(i)))                start = Math.max(map.get(s.charAt(i)) + 1, start);            maxlen = Math.max(i - start + 1, maxlen);            map.put(s.charAt(i), i);        }        return maxlen;    }    public static void main(String[] args) {        // TODO Auto-generated method stub        Scanner scanner = new Scanner(System.in);        String s = scanner.nextLine();        int maxlen = lengtnhOfLongestSubstring(s);        System.out.println(maxlen);    }}

Python

class Solution:    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        maxlen = 0        start = 0        hash_map = {}        for i in range(len(s)) :            if s[i] in hash_map :                start = max(hash_map[s[i]] + 1, start)            maxlen = max(i - start + 1, maxlen)            hash_map[s[i]] = i        return maxlenif __name__ == '__main__' :    s = 'abcabcbb'    solution = Solution()    maxlen = solution.lengthOfLongestSubstring(s)    print(maxlen)
0 0