Leetcode No.171 Excel Sheet Column Number Excel表格列數(c++實現)
阿新 • • 發佈:2021-08-02
1. 題目
1.1 英文題目
Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number.
1.2 中文題目
給你一個字串 columnTitle ,表示 Excel 表格中的列名稱。返回該列名稱對應的列序號。
1.3輸入輸出
輸入 | 輸出 |
---|---|
columnTitle = "A" | 1 |
columnTitle = "AB" | 28 |
columnTitle = "ZY" | 701 |
columnTitle = "FXSHRXW" | 2147483647 |
1.4 約束條件
- 1 <= columnTitle.length <= 7
- columnTitle consists only of uppercase English letters.
- columnTitle is in the range ["A", "FXSHRXW"].
2. 分析
2.1 一般演算法
這道題類似於26進位制轉化為十進位制的問題,因此可以類比進位制轉換的“加權求和法”,具體程式碼如下:
class Solution { public: int titleToNumber(string columnTitle) { int num = 0; for (int i = columnTitle.size() - 1; i >= 0; i--) { num += (columnTitle[i] - 'A' + 1) * pow(26, columnTitle.size() - 1 - i); } return num; } };
2.2 優化求和演算法
考慮到pow函式時間複雜度較高,可利用遞推進行求解。程式碼如下:
class Solution {
public:
int titleToNumber(string columnTitle) {
int num = 0;
for (int i = 0; i < columnTitle.size(); i++) {
num = columnTitle[i] - 'A' + 1 + num * 26;
}
return num;
}
};
2.2 c++11優化演算法
對於迴圈部分,可以用c++11進行優化。程式碼如下:
class Solution {
public:
int titleToNumber(string columnTitle) {
int num = 0;
for (auto element:columnTitle) {
num = element - 'A' + 1 + num * 26;
}
return num;
}
};
作者:雲夢士
出處:http://www.cnblogs.com/yunmeng-shi/
本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,並保留此段宣告,否則保留追究法律責任的權利。