当前位置:网站首页>leetcode每日一题:字符串中的第一个唯一字符
leetcode每日一题:字符串中的第一个唯一字符
2022-07-05 17:17:00 【利刃Cc】

链接:字符串中的第一个唯一字符
(注:该题提示字符串只包含小写字母)
常规思路:对每个字符都进行一次遍历,查找是否字符串中是否有相同的字母。(但是最坏情况下时间复杂度为O(n^2),所以这里不推荐)
代码:
class Solution {
public:
int firstUniqChar(string s) {
//常规思路:每次都遍历查找是否有相等的,时间复杂度O(n^2),不推荐
for(size_t i = 0; i < s.size(); i++)
{
//用flag用做标记,若变为0说明有相同的
int flag = 1;
for(size_t j = 0; j < s.size(); j++)
{
//若下标相同则不需要对比
if(j == i)
continue;
if(s[j] != s[i])
continue;
else
{
flag = 0;
break;
}
}
if(flag == 1)
return i;
}
return -1;
}
};
另一种思路: 使用计数排序的思想,统计字符串中每个字母出现的次数,然后再将第一个计数数组中为1的字母返回。
注:该思路的时间复杂度为O(N)。
代码:
class Solution {
public:
int firstUniqChar(string s) {
// 时间复杂度为O(n)
// 利用计数排序的思想,先统计每个字母出现的次数
int arr[26] = {
0};
for(size_t i = 0; i < s.size(); i++)
{
arr[s[i] - 'a']++;
}
//查找s中对应arr出现的次数是否为一次
for(size_t i = 0; i < s.size(); i++)
{
if(arr[s[i] - 'a'] == 1)
return i;
}
return -1;
}
};

边栏推荐
- Short the command line via jar manifest or via a classpath file and rerun
- Cartoon: a bloody case caused by a math problem
- To solve the problem of "double click PDF file, pop up", please install Evernote program
- stirring! 2022 open atom global open source summit registration is hot!
- 得知女儿被猥亵,35岁男子将对方打至轻伤二级,法院作出不起诉决定
- 企业数字化发展中的六个安全陋习,每一个都很危险!
- How MySQL uses JSON_ Extract() takes JSON value
- Tips for extracting JSON fields from MySQL
- Flow characteristics of kitchen knife, ant sword, ice scorpion and Godzilla
- Example tutorial of SQL deduplication
猜你喜欢

ICML 2022 | Meta propose une méthode robuste d'optimisation bayésienne Multi - objectifs pour faire face efficacement au bruit d'entrée

Oracle Recovery Tools ----oracle数据库恢复利器

求解为啥all(())是True, 而any(())是FALSE?

MySQL之知识点(六)
Redis+caffeine two-level cache enables smooth access speed

Winedt common shortcut key modify shortcut key latex compile button
In depth understanding of redis memory obsolescence strategy

提高应用程序性能的7个DevOps实践

CVPR 2022 best student paper: single image estimation object pose estimation in 3D space
MYSQL group by 有哪些注意事项
随机推荐
漫画:一道数学题引发的血案
Machine learning 02: model evaluation
How to write a full score project document | acquisition technology
MYSQL group by 有哪些注意事项
Redis+caffeine two-level cache enables smooth access speed
Read the history of it development in one breath
中国银河证券开户安全吗 开户后多久能买股票
Seven Devops practices to improve application performance
SQL Server(2)
漫画:有趣的【海盗】问题
[7.7 live broadcast preview] the lecturer of "typical architecture of SaaS cloud native applications" teaches you to easily build cloud native SaaS applications. Once the problem is solved, Huawei's s
外盘黄金哪个平台正规安全,怎么辨别?
mongodb(快速上手)(一)
关于mysql中的json解析函数JSON_EXTRACT
C#(Winform) 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件
漫画:寻找无序数组的第k大元素(修订版)
漫画:如何实现大整数相乘?(下)
读libco保存恢复现场汇编代码
Accuracy of BigDecimal Division
MySQL之知识点(七)