2012-05-08 40 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(); 


}