经典算法题之删列造序(二)

解决方案

方法一:直接遍历思路和算法

题目要求删除不是按字典序升序排列的列,由于每个字符串的长度都相等,我们可以逐列访问字符串数组,统计不是按字典序升序排列的列。

对于第 j 列的字符串,我们需要检测所有相邻字符是否均满足 strs i−1 j ≤ strs i j 。

代码

Java

复制代码
class Solution {
    public int minDeletionSize(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].charAt(j) > strs[i].charAt(j)) {
                    ans++;
                    break;
                }
            }
        }
        return ans;
    }
}

C++

复制代码
class Solution {
public:
    int minDeletionSize(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;
    }
};

C

复制代码
int minDeletionSize(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;
}

复杂度分析

时间复杂度:O(m×n),其中 m 为字符串数组的长度,n 为数组中每个字符串的长度,判定每一列的的字典序需要遍历字符串数组每一列,因此时间复杂度为 O(m×n)。

空间复杂度:O(1)。

相关推荐
geovindu15 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗17 小时前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
路灯中转站17 小时前
数据结构C语言版(什么是数据类型)
数据结构
凌冰_17 小时前
数据结构 - 队列(五)
数据结构·算法·软件工程
让我们一起加油好吗18 小时前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
让我们一起加油好吗19 小时前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
lisw051 天前
稀疏算法概述!
算法·机器人·无人机
YLCHUP1 天前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴1 天前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu1 天前
python:Logistic Regression
开发语言·后端·python·算法