2016-08-24 110 views
-3

我解決這裏給出的HackerRank問題: - https://www.hackerrank.com/challenges/bigger-is-greater分割故障(核心轉儲)編程用C

程序語句如下:

給定一個詞,重新排列的字母來構建另一個詞按照字典順序大於原始詞的方式。如果有多個可能的答案,請找到其中的詞典中最小的一個。

如果你不明白,那麼只要去鏈接;他們用例子來解釋。

我做了下面給出的程序。在這個程序中我做了二維數組。並且變量t決定行數和數量是否修復。

代碼正在運行,因爲它應該是t = 1。 但是,當t大於1或一些大量它給錯誤分割錯誤

代碼是如下:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main() { 

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int i,j,n,rot; 
    int t; 
    scanf("%d",&t); 
    char c[t][100]; 
    char temp; 
    for(int i=0;i<t;i++) 
    { 
     scanf(" %s",c[i]); 
    } 
    rot=t; 
    for(int t=0;t<rot;t++) 
    { 
     n = strlen(c[t]); 
     //printf("%d\n",n); 
     for(i=n-1;i>=0;i--) 
     { 
      for(j=i-1;j>=0;j--) 
      { 
       //printf("comparint %c and %c\n",c[t][i],c[t][j]); //FOR DEBUG 
       if(c[t][i]>c[t][j]) goto gotit; 
      } 
     } 
     printf("no answer\n"); 

     continue; 

    gotit: 
     temp = c[t][i]; 
     c[t][i]=c[t][j]; 
     c[t][j]=temp; 
     n = (n-1)-j; 
     //printf("%s\n",c[t]); //FOR DEBUG 
     //printf("%d %d %d\n",i,j,n); //FOR DEBUG 

     for(i=0;i<n-1;i++) 
     { 
      for(int k=0;k<n-1;k++) 
      { 
       // printf("comparint %c and %c\n",c[t][j+k+1],c[t][j+k+2]); 
       if(c[t][j+k+1]>c[t][j+k+2]) 
       { 
        temp = c[t][j+k+1]; 
        c[t][j+k+1]=c[t][j+k+2]; 
        c[t][j+k+2]=temp; 
       } 
      } 
     } 
     printf("%s\n",c[t]); 
    } 

    return 0; 
} 
+1

開始簡單 - 解決您的壓痕。 –

+0

如果我能解決這個問題,我會直接提交給Hacker Rank,但感謝有機會成爲您的代理人。這些網站是關於*你的*能力的。 –

+0

分段故障發生在哪條線上?您應該嘗試用調試器逐步執行程序,在各個步驟中檢查字符串的值以查看它們何時已經損壞。 – Barmar

回答

0

t可以是10^5或100,000。您的c數組爲c[t][100],因此其大小爲100000 * 100,即10,000,000。你可能會遇到堆棧溢出。

正如WhozCraig指出的那樣,每個案件的處理都是獨立的。因此,c可以是一維數組:char c[100]。將所有c[t][...]更改爲c[...]

調整的東西,讓你有一個外循環:

int 
main() 
{ 
    int t; 
    char c[100]; 

    scanf("%d", &t); 

    for (int i = 0; i < t; i++) { 
     scanf(" %s", c); 
     // do all processing for this line ... 
     n = strlen(c); 
    } 

    return 0; 
}