当前位置:网站首页>leetcode.14 --- 最长公共前缀
leetcode.14 --- 最长公共前缀
2022-06-25 22:18:00 【_End丶断弦】
最长公共前缀

思路:
代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";//特判strs为空
int row = strs.size(); //行
int col = strs[0].size();//列
for(int i = 0;i < col;i++){
//先从列开始循环
int fisrtChar = strs[0][i]; //第一个字符串
for(int j = 1;j < row;j++){
//第2层循环从1开始,第一行的字符串已经取出来了
if(strs[j].length() == i || strs[j][i] != fisrtChar)
return strs[0].substr(0,i); //若当前行的字符串走完或者当前j行i列和firstChar
//不同则返回str[0]从0到i的子串
}
}
//循环结束还没返回则公共前缀就是str[0]
return strs[0];
}
};
时间复杂度:O(mn),m 是字符串数组中的字符串的平均长度,n是字符串的数量,最坏每个字符都比较一次
空间复杂度:O(1)
边栏推荐
- Explain in detail the three types of local variables, global variables and static variables
- SSH review
- Smt贴片机工作流程
- 19c安装psu 19.12
- Notes on the method of passing items from the spider file to the pipeline in the case of a scratch crawler
- Redis jump table
- About Simple Data Visualization
- 原型和原型链的理解
- 使用coe_load_sql_profile.sql固定执行计划
- Servlet response下载文件
猜你喜欢

小红书微服务框架及治理等云原生业务架构演进案例

Literature research (III): overview of data-driven building energy consumption prediction models

About Simple Data Visualization

What is micro service

Thrift getting started

DHCP review

【ROS进阶篇】第一讲 常用API介绍

(Reprint) visual explanation of processes and threads

JS to input the start time and end time, output the number of seasons, and print the corresponding month and year

Some common operation methods of array
随机推荐
DNS复习
Linux下搭建集群环境(2)-----------linux下安装Mysql
Network protocol: detailed explanation of redis protocol
11.1.1、flink概述_flink概述
ORA-01153 :激活了不兼容的介质恢复
SPI锡膏检查机的作用及原理
7. common instructions (Part 2): common operations of v-on, v-bind and V-model
DHCP review
Smt贴片机保养与维护要点
ValueError: color kwarg must have one color per data set. 9 data sets and 1 colors were provided
SSL unresponsive in postman test
Redis之内存淘汰机制
POSTMAN测试出现SSL无响应
深圳台电:联合国的“沟通”之道
smt贴片加工行业常见术语及知识汇总
Reading notes on how to connect the network - hubs, routers and routers (III)
每日刷题记录 (四)
ASA如何配置端口映射及PAT
About the solution to prompt modulenotfounderror: no module named'pymongo 'when running the scratch project
19c installing PSU 19.12
