Leetcode 3. Longest Substring Without Repeating Characters

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

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        /*
        动态规划
        dp[k]为以k为结尾的最长无重复子串
        last_index[x]是x上一次出现的位置,若未出现过即为-1
        dp[k]=min(dp[k-1]+1,k-last_index[s[k]])
        
        边界条件:
        1.输入为空,直接输出0
        2.dp[0]=1,循环从1开始
        */
        #include<algorithm>
        using namespace std;
        if(s.empty()) return 0;
        int last_index[130];
        //init
        for(int i=0;i<130;++i) last_index[i]=-1;
        vector<int> dp(s.size(),1);//dp[0]=1
        last_index[s[0]]=0;
        int ans=1;
        //
        for(int k=1;k<s.size();++k){
            dp[k]=min(dp[k-1]+1,k-last_index[s[k]]);
            last_index[s[k]]=k;
            ans=max(ans,dp[k]);
        }
        return ans;
    }
};

 python版本

def _init(L):
    last_index={}
    dp=[0 for i in range(L)]
    return dp,last_index
def _process(dp,last_index,s):
    L=len(dp)
    for k in range(L):
        if k==0:
            dp[k]=1
        else:
            dp[k]=min(dp[k-1]+1,k-last_index.get(s[k],-1))
        last_index[s[k]]=k
    return max(dp)
class Solution:
    '''
    动态规划
    dp[k]以k位置字符为结尾的最长子串长度
    last_index[x] x字符上一次出现的位置
    init:
        last_index[]=-1
        dp[]=0
    process:
        k!=0
            dp[k]=min(dp[k-1]+1,k-last_index[s[k]])
        k==0
            dp[k]=1
    '''
    def lengthOfLongestSubstring(self, s: str) -> int:
        if len(s)==0: return 0
        dp,last_index=_init(len(s))
        return _process(dp,last_index,s)

 

posted @ 2019-04-24 17:08  benda  阅读(94)  评论(0编辑  收藏  举报