zoukankan      html  css  js  c++  java
  • Plateau problem

    Given a sorted array in non-descending order, the element type can be positive integer or char, return the length of the longest consecutive segments

    Example,

    Input:"1223334556", output 3

    Input:  "abccdef", output 2

     

    This problem is call the Plateau problem, and it has once confused the famous computer scientist David Gries

    Here is a solution

    int length = 0;
    for (int i = 0; i < s.Length; i++)
    {
        
    if (s[i] == s[i - length])
            length
    ++;
    }
    return length;

     

    the idea is that, first let length = 0;

    than increase length when the next char is same as the start char, suppose you are start at index i, and length = 0, it is obviousely s[i] == s[i – length]; since any char equals to itself.

    then if the char at position i + 1 equals to current char,increase the length by 1, else do nothing.

    Note that, the given string must be in non-descending order, otherwise, this method will not work.

     

    Take a look at the example below

    "11212", you will get the result 3, but not 2, why?

    When you move to the first ‘2’, the condition in the if statement is false, and current length is 2, since there are two consecutive 1s in the front of the string, then you move to the last 1, and this time the if condition is true,since the second 1 equals to the last 1, and you got length increased by 1, thus the result is 3, and that’s a incorrect result. This was all caused by the given string which was not in non-descending order.

     

    The time complexity of above code is O(n), where n is the length of the given string.

    The following code is performs a little better, which has a complexity of O(n – maxLen), where maxLen is the length of the longest consecutive segment in the given string.

     

    Code

     

    How about remove the condition, let the array in any order, for example 11212, returns 2, not 3

    We can record the current length, and define another variable maxLen to hold the final result, each time we met the different char, let curLen = 0, and count the next loop. else, increase curLen, and update maxLen if it greater than maxLen.

    code like

     

    Code

    and further more, if i want to return the longest consecutive string

    you should use another int to record the position when the index stop increasing.

    Code

     

  • 相关阅读:
    ECSHOP给分类添加图
    windows2008一键安装环境的配置说明
    在css中定义滚动条样式
    登录不到phpmyadmin
    dedecms程序给栏目增加缩略图的方法
    httpd.conf
    关于 equals() 与 hashCode() 个人理解总结
    postman 安装失败 Failed to install the .NET Framework, try installingthe latest version manully
    docker 私有仓库The push refers to repository [x:5000/test] Get https://x:5000/v2/: dial tcp x:5000: conn
    Redis window 和 Linux 环境下的搭建
  • 原文地址:https://www.cnblogs.com/graphics/p/1497515.html
Copyright © 2011-2022 走看看