zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters

    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.

    本题是典型的动态规划问题。

    主干思想:以abcabcbb为例,这个字符串的最大字串是 (不包含最后一个b的剩余字符串的abcabcb的最大字串) 和 (包含最后一个b的最大不重复字串)中较大值。

    编写程序实现。

     dynamic函数中的形参last表示字符串s的最大下标,及长度减去1的值。因为在c语言中仅仅通过s无法知道它的大小。

    calcul_include_last函数用于计算包含最后一个字符的最长不重复子串。formor表示包含最后一个字符的最长不重复子串的左下标。

     1 int calcul_include_last(char *s, int last) {
     2     int formor = 0;
     3     for(int i=last; i>formor; i--) {
     4         for(int j=i-1; j>=formor; j--)
     5         if(s[i]==s[j]) {formor = j+1; break;}
     6     }
     7     return last-formor+1;
     8 }
     9 
    10 int dynamic(char *s, int last) {
    11     if (last==0) return 1;
    12     
    13     int compare1 = dynamic(s, last-1);
    14     int compare2 = calcul_include_last(s, last);
    15     if(compare1 > compare2) 
    16         return compare1;
    17     else 
    18         return compare2;
    19 }
    20 
    21 int lengthOfLongestSubstring(char* s) {
    22     if(!strlen(s)) return 0;
    23     
    24     return dynamic(s, strlen(s)-1);
    25 }
  • 相关阅读:
    SQL SERVER 存储过程或触发器等优化SET NOCOUNT ON
    C#以16进制接收串口数据
    DevExpress中的RichEditControl(富文本)控件,如何把滚动条移动至最后!
    DevExpress中XtraReport的XRRichText在打印时,打印不出内容问题
    DevExpress控件GridControl如何在页脚进行汇总
    创建虚拟机SQL server
    接口,抽象类
    Linq 优化
    sql 优化
    C#:Hashtable和Dictionary
  • 原文地址:https://www.cnblogs.com/midhillzhou/p/8625398.html
Copyright © 2011-2022 走看看