力扣每日一题-查询网格图中每一列的宽度-2024.4.27

力扣题目:查询网格图中每一列的宽度

题目链接:2639.查询网格图中每一列的宽度

题目描述

代码思路

双层for循环遍历整个矩阵容易想到,只要能想到使用整数转字符串的技巧("" + 字符串),即可完成题目

代码纯享版

java 复制代码
class Solution {
    public int[] findColumnWidth(int[][] grid) {
        int[] ans = new int[grid[0].length]; 
        for(int i = 0; i < grid[0].length; i++){
            int max = 0;
            for(int j = 0; j < grid.length; j++){
                String str = "" + grid[j][i];
                
                max = Math.max(max, str.length());
            }
            ans[i] = max;
        }
         return ans;
    }
}

代码逐行解析版

java 复制代码
class Solution {
    public int[] findColumnWidth(int[][] grid) {
        int[] ans = new int[grid[0].length]; //创建ans整数数据,记录每一列的宽度,即字符串长度最大值
        for(int i = 0; i < grid[0].length; i++){ 
            int max = 0; //记录最大值
            for(int j = 0; j < grid.length; j++){
                String str = "" + grid[j][i]; //将整数变成字符串,方便用字符串的length()方法直接计算字符串长度
                
                max = Math.max(max, str.length()); //记录最大值
            }
            ans[i] = max; //添加最大值
        }
         return ans;
    }
}
相关推荐
2301_8227032016 分钟前
鸿蒙Flutter第三方库FlutterUnit组件百科适配——具体示例还原演示1
算法·flutter·华为·harmonyos·鸿蒙
FuckPatience23 分钟前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
2301_764441337 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI7 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
014-code7 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024067 小时前
组合模式(Composite Pattern)
开发语言
Billlly7 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives8 小时前
atcoder ABC 452 题解
数据结构·算法
游乐码8 小时前
c#泛型约束
开发语言·c#
Dontla8 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang