classSolution: defminDeletionSize(self, strs: List[str]) -> int: returnsum(any(x > y for x, y in pairwise(col)) for col inzip(*strs)) # 空间复杂度为 O(m),改用下标枚举可以达到 O(1)
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicintminDeletionSize(String[] strs) { introw= strs.length; intcol= strs[0].length(); intans=0; for (intj=0; j < col; ++j) { for (inti=1; i < row; ++i) { if (strs[i - 1].charAt(j) > strs[i].charAt(j)) { ans++; break; } } } return ans; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intminDeletionSize(vector<string>& strs){ int row = strs.size(); int col = strs[0].size(); int ans = 0; for (int j = 0; j < col; ++j) { for (int i = 1; i < row; ++i) { if (strs[i - 1][j] > strs[i][j]) { ans++; break; } } } return ans; } };
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolution { publicintMinDeletionSize(string[] strs) { int row = strs.Length; int col = strs[0].Length; int ans = 0; for (int j = 0; j < col; ++j) { for (int i = 1; i < row; ++i) { if (strs[i - 1][j] > strs[i][j]) { ans++; break; } } } return ans; } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
intminDeletionSize(char ** strs, int strsSize) { int row = strsSize; int col = strlen(strs[0]); int ans = 0; for (int j = 0; j < col; ++j) { for (int i = 1; i < row; ++i) { if (strs[i - 1][j] > strs[i][j]) { ans++; break; } } } return ans; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11
funcminDeletionSize(strs []string) (ans int) { for j := range strs[0] { for i := 1; i < len(strs); i++ { if strs[i-1][j] > strs[i][j] { ans++ break } } } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var minDeletionSize = function(strs) { const row = strs.length; const col = strs[0].length; let ans = 0; for (let j = 0; j < col; ++j) { for (let i = 1; i < row; ++i) { if (strs[i - 1][j] > strs[i][j]) { ans++; break; } } } return ans; };
复杂度分析
时间复杂度:O(m \times n),其中 m 为字符串数组的长度,n 为数组中每个字符串的长度,判定每一列的的字典序需要遍历字符串数组每一列,因此时间复杂度为 O(m \times n)。