第1章陣列和字串 6 8題 倒計時23天

2021-06-27 03:17:52 字數 1832 閱讀 7576

病了一場,家庭瑣事太多,耽擱了好些日子。看來後面得抓緊時間了!

6. 一幅影象由n x n矩陣的畫素點組成,每個畫素點4個位元組的資訊量,將影象順時針(逆時針)旋轉90度。如何做到?

思路:剝洋蔥法,由外而內分層進行,以4x4大小的畫素點矩陣為例,先從最外圈(黃色)開始調整,然後是內圈(綠色)。

程式設計實現:

/*

@ clockwise rotate a matrix n x n

*/void rotatematrix(int** matrix, int n)

}}

部分測試**:

const int n = 10;

int **pmatrix = new int*[n];

for(int i=0; i

7.m x n大小矩陣中某個元素為0, 則將該元素所在的行和列均置為0

思路:這道題看似簡單,其實暗藏機關。如果遍歷矩陣,遇到0元素,則將所在行和列均置為0,最後得到0矩陣。為什麼呢?不明白的時候可以找個簡單的例子推理。一種可行的方法是第一次遍歷時候記錄下0元素所在的行和列,然後在第二次遍歷時將所在行或者列為0的元素置為0即可。

程式設計實現:

/*@ if an element in a mxn matrix is 0, its entire row and column is set to 0.

*/void setzeros(int** matrix, int m, int n)

; int **pmatrix = new int*[m];

for(int i=0; i

8. 假設已有issubstring方法去判斷乙個字串是否為另乙個的子字串;現有s1和s2兩個字串,呼叫一次issubstring方法判斷兩者是否互為旋轉式?如「waterbottle」和「bottlewater」互為旋轉式。

思路:簡單清晰,方法如下:1) 先檢查s1和s2的長度是否相等,不等顯然不能滿足互為旋轉式;2)將s1首尾鏈結組成乙個新的字串s11,然後呼叫issubstring判斷s2是否為s1的乙個字串。

程式設計實現:

/*@ judge s is substring of t or not.

*/bool issubstring(const string& s, const string& t)

return false;

}

部分測試**如下:

//test issubstring

string str1 = "world";

string str2 = "hello wor2ldworworld";

if(issubstring(str1, str2))

cout << str1 << " is substring of " << str2 << endl;

else

cout << str1 << " is not substring of " << str2 << endl;

string str3 = "ldwor";

if(isrotatestring(str1,str3))

cout << str1 << " is rotated by " << str3 << endl;

else

cout << str1 << " is not rotated by " << str3 << endl;

第1章 字串

字串是程式中經常使用的一種資料型別。串,顧名思義就是一些列單個元素的連線組合,那麼字串也就是由一系列單個字元連線而成。在上一堂課上,我們有一行 是 std cout hello world 這行 中,我給大家介紹了兩個c 標準庫物件以及使用方法。但是其中的 hello world 我沒有給大家解釋,...

第5章 陣列與字串

5.1 陣列array 5.1.1 陣列的概念 語法 型別陣列名 型別陣列名 元素個數 不能定義長度為 0的陣列,即 裡不能是 05.1.2 記憶體中的陣列 獲得陣列的尺寸 即元素的個數 int n sizeof a sizeof int 5.1.3 陣列的初始化 初始化時,右值由 括起一組初始值列...

第3章 陣列與字串

程式3.1 逆序輸出 讀入一些整數,不超過100個,逆序輸出到一行中 include define maxn 105 常常難以精確計算出需要的陣列大小,陣列一般會比宣告的稍大一點,會更保險 int buf maxn 因為區域性變數存放在堆疊段中,若放在函式體內可能會導致棧溢位,一般在全域性部分宣告較...