2012-05-08 38 views
0

我有10个项目子序列号

int list[] = {2,3,8,9,10,11,12,2,6,8}; 
int start_pos = 0; 
int lenght=0; // lenght of the sub-~consetuve 
for (int a =0; a <=9; a++) 
{ 

    if ((list[a]+1) == (list[a+1])) { 
     // continue just the string; 
     lenght++; 
    } else { 
     start_pos = a; 
    } 
} 
cout << lenght << " and start in " << start_pos; 
getchar(); 

,但它不工作得到最长连续越来越多的阵列,它应该在长度返回& START_POS(3 lenght 4)因为最长的增长是从9,10,11,12,但它不起作用。

+9

告诉我们一些代码Bill :) –

+0

我认为你的一个问题可能会溢出。在C++中整数的最大大小是一样的,一旦超过,就会回到 - (最大值)。 – Whovian

+1

这不是最长的*子序列*,它是最长的*连续运行*。 – dasblinkenlight

回答

0

假设你实际上的意思是子序列,只需猜测序列开头的数字,然后运行线性扫描。如果你的意思是子串,那就更简单了 - 作为OP的练习。

线性扫描是这样的:

char next = <guessed digit>; 
int len = 0; 
char *ptr = <pointer to input string>; 
while (*ptr) { 
    if ((*ptr) == next) { 
    next = next + 1; 
    if (next > '9') next = '0'; 
    len++; 
    } 
    ptr++; 
} 

现在包装与一个循环,将所有的数字从“0”到“9”和你做,挑一个,让长度最长。

+0

这不适用于像“401401403404405”这样的序列(401,402,403,404,405) – dasblinkenlight

+0

我认为你正在解决与我不同的问题。我明白他正在寻找数字按顺序0,1,2,3,4,...,9的最长子序列,然后环绕。 –

+0

我同意这也是一个有效的解释 - 在OP中的问题肯定是未定义的。 – dasblinkenlight

0

简单的想法:序列的起点,终点和长度。

运行环路I

序列将开始每当当前数量(在索引i)小于下一个号码1 =>开始点集= I

何时结束条件上述假=>获得终点= >获得长度=结束-start(让更多的变量称为最大比较长度)=>结果可能是最大,复位重新开始,终点= 0时,序列

0

末我自己做的:

#include <iostream> 

using namespace std; 
bool cons(int list[] , int iv) { bool ret=true; for (int a=0; a<=iv; a++) { if (list[a] != list[a+1]-1) ret=false; } return ret; } 

void main() { 
int str[10] = {12,13,15,16,17,18,20,21}; 
int longest=0; 
int pos=0; 
for (int lenght=1; lenght <= 9; lenght++) { 
    int li[10]; 
    for (int seek=0; seek <= 9; seek++) { 
     for (int kor=0; kor <= lenght-1; kor ++) { 
      li[kor] = str[seek+kor]; 
     } 
     if (cons(li , lenght-2)) { 
      longest = lenght; 
      pos=seek; 
     } 
    } 
} 

for (int b=pos; b <= pos+longest-1; b++) cout << str[b] << " - "; cout << "it is the end!" << endl; getchar(); 


}