為學論壇“每日一題”系列---最短的包含字串(待驗證正確性)

來源:互聯網
上載者:User

題目:

給出一個字串,求該字串的一個子串S,S包含A-Z中的全部字母,並且S是所有合格子串中最短的,輸出S的長度。如果給出的字串中並不包括A-Z中的全部字母。如果無解輸出-1。

輸入 串S

長度 <= 100000。

我的做法:

大概做法和我之前做過的一題根本相同,參見這個:字串的故事

代碼:

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<memory.h>const int N = 1000 ;int main(void){int i,j,n,nBeg,nEnd,nLen,nMinLen,nSeqLen ;int b[N] ;char szStr[N] ;char szQueue[N] ;freopen("in.txt","r",stdin) ;while(gets(szStr) != NULL){memset(b,-1,sizeof(b)) ;memset(szQueue,0,sizeof(szQueue)) ;nBeg = nEnd = -1 ;nLen = strlen(szStr) ;n = 0 ;nMinLen = -1 ;for(i = 0 ; i < nLen ; ++i){if(szStr[i] >= 'a' && szStr[i] <= 'z'){if(-1 == nBeg){nBeg = 0 ;n += 1 ;nEnd++ ;szQueue[nEnd] = szStr[i] ;b[szStr[i]-'a'] = nBeg  ;}else if(n >= 26 && szStr[i] == szQueue[nBeg]){nEnd++ ;szQueue[nEnd] = szStr[i] ;szQueue[b[szStr[i]-'a']] = '\0' ;b[szStr[i]-'a'] = nEnd ; //for(j = nBeg + 1 ; j < nEnd ; ++j){if(szQueue[j] != '\0'){nBeg = j ;break ;}}nSeqLen = nEnd + 1 - nBeg ;if(nSeqLen < nMinLen){nMinLen = nSeqLen ;}}else if(szStr[i] == szQueue[nBeg] && n < 26){nEnd++ ;szQueue[nEnd] = szStr[i] ;szQueue[b[szStr[i]-'a']] = '\0' ;b[szStr[i]-'a'] = nEnd ; //for(j = nBeg + 1 ; j <= nEnd ; ++j){if(szQueue[j] != '\0'){nBeg = j ;break ;}}}else if(b[szStr[i]-'a'] != -1){nEnd++ ;szQueue[nEnd] = szStr[i] ;szQueue[b[szStr[i]-'a']] = '\0' ;b[szStr[i]-'a'] = nEnd ; //}else {nEnd++ ;szQueue[nEnd] = szStr[i] ; n += 1 ;b[szStr[i]-'a'] = nEnd ;if(n >= 26){nMinLen = nEnd + 1 - nBeg ;}}} //if} //forprintf("%d\n",nMinLen) ;} //whilereturn 0 ;}

我自己的測試資料:

abcdefghijklmnopqrstiiuvwxyzzzzaaaaaaaabcdeeeeeeabcdeedcbaabcdeabcbcedbacedababeabaeceeedddcccbbbaaaabbccdde

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.