C++程式:查詢電話號碼中的國家程式碼長度


假設我們有一個包含n個數字字串的字串列表S。Amal在一個城市有n個朋友。Amal知道所有朋友的電話號碼:它們儲存在S中。S中的所有字串長度相同。Amal需要找出城市的區號。他假設城市的區號是所有朋友電話號碼的最長公共字首。我們需要找到城市區號的長度。

問題類別

為了解決這個問題,我們需要操作字串。程式語言中的字串是儲存在特定陣列型別中的字元流。幾種語言將字串指定為特定資料型別(例如Java、C++、Python);而其他幾種語言將字串指定為字元陣列(例如C)。字串在程式設計中非常重要,因為它們通常是各種應用程式中首選的資料型別,並用作輸入和輸出的資料型別。有各種字串操作,例如字串搜尋、子串生成、字串剝離操作、字串轉換操作、字串替換操作、字串反轉操作等等。檢視下面的連結,瞭解如何在C/C++中使用字串。

https://tutorialspoint.tw/cplusplus/cpp_strings.htm

https://tutorialspoint.tw/cprogramming/c_strings.htm

因此,如果我們問題的輸入類似於S = ["00209", "00219", "00999", "00909"],則輸出將為2,因為區號是“00”。

步驟

為了解決這個問題,我們將遵循以下步驟:

n := size of S
ans := 0
m := size of S[0]
for initialize i := 0, when i < m, update (increase i by 1), do:
   c := S[0, i]
   for initialize j := 0, when j < n, update (increase j by 1), do:
      if S[j, i] is not equal to c, then:
         return ans
   (increase ans by 1)
return ans

示例

讓我們看看下面的實現來更好地理解:

#include <bits/stdc++.h>
using namespace std;
int solve(vector<string> S){
   int n = S.size();
   int ans = 0;
   int m = S[0].size();
   for (int i = 0; i < m; i++){
      char c = S[0][i];
      for (int j = 0; j < n; j++){
         if (S[j][i] != c){
            return ans;
         }
      }
      ans++;
   }
   return ans;
}
int main(){
   vector<string> S = { "00209", "00219", "00999", "00909" };
   cout << solve(S) << endl;
}

輸入

{ "00209", "00219", "00999", "00909" }

輸出

2

更新於:2022年4月7日

470 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.