DP思路解算法题

来源:互联网 发布:dota2战绩查询软件 编辑:程序博客网 时间:2024/06/01 14:43

今天首次接触到DP算法,DP是dynamic programming的缩写,中文为动态规划编程,是一种编程思想。

LeetCode上这么一道题:

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

Examples:

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.

这道题乍看下感觉很简单,但实际动手写了一段代码发现自己都被多层循环搞糊涂了,而且蛮力解法时间复杂度太高,最后不得不参考答案后才恍然大悟,了解了DP的思想。

希望大家先自己思考下,动手写下自己的解法,然后再看下面的解法,觉得有一种惊奇的感觉,然后你会发现算法真的可以开阔思维。

下面贴出DP解法:

C版本:

#include<stdio.h>#include<string.h>int LenOfSubstr(const char* s){    int pos[256];    memset(pos, -1, sizeof(int)*256);    int maxlen = 0;    int start = -1;    for (int i = 0; i < strlen(s); i++){        if (pos[s[i]] > start){            start = pos[s[i]];        }        maxlen = maxlen > (i-start) ? maxlen : (i-start);        pos[s[i]] = i;    }    return maxlen;}int main(){  char* s = "abcabcbb";  printf("maxlen of \"%s\" is %d\n", s, LenOfSubstr(s));}

python版本:

# -*-coding:utf-8-*-def lenOfSubstr(s):        dc = {}        start = -1        maxlen = 0        for i in range(len(s)):            if s[i] in dc:                if dc[s[i]] > start:                    start = dc[s[i]]            maxlen = max(maxlen,i-start)            dc[s[i]] = i        return maxlens = 'pwwkew'print(lenOfSubstr(s))


1 0
原创粉丝点击