Leecode刷题之旅-C语言/python-387 字符串中的第一个唯一字符
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Leecode刷题之旅-C语言/python-387 字符串中的第一个唯一字符,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1833字,纯文字阅读大概需要3分钟。
内容图文
![Leecode刷题之旅-C语言/python-387 字符串中的第一个唯一字符](/upload/InfoBanner/zyjiaocheng/836/aa736ee90ae4460db30553c428f85d5f.jpg)
/* * @lc app=leetcode.cn id=387 lang=c * * [387] 字符串中的第一个唯一字符 * * https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/ * * algorithms * Easy (36.55%) * Total Accepted: 23.7K * Total Submissions: 64.7K * Testcase Example: '"leetcode"' * * 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 * * 案例: * * * s = "leetcode" * 返回 0. * * s = "loveleetcode", * 返回 2. * * * * * 注意事项:您可以假定该字符串只包含小写字母。 * */ int firstUniqChar(char* s) { int count[26]; for(int i=0;i<26;i++){ count[i]=0; } for(int i=0;i<strlen(s);i++){ count[s[i]-'a']++; } for(int i=0;i<strlen(s);i++){ if(count[s[i]-'a']==1){ return i; } } return -1; }
这里和之前一个题类似,就是设置一个字母表,0代表a,以此类推,初始化都为0。
然后在s中逐一的计数,统计各个字母的次数。
然后再从头循环,如果这个字母的次数为一的话,直接return当前的位置。
------------------------------------------------------------------------------------------------------------
python:
# # @lc app=leetcode.cn id=387 lang=python3 # # [387] 字符串中的第一个唯一字符 # # https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/ # # algorithms # Easy (36.55%) # Total Accepted: 23.7K # Total Submissions: 64.7K # Testcase Example: '"leetcode"' # # 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 # # 案例: # # # s = "leetcode" # 返回 0. # # s = "loveleetcode", # 返回 2. # # # # # 注意事项:您可以假定该字符串只包含小写字母。 # # class Solution(object): def firstUniqChar(self, s): list1=[] list2=[] if len(s)==1: return 0 elif len(s)==2: if s[0]==s[1]: return -1 else: return 0 elif len(s)!=0: s1="".join(list(set(s))) for i in s1: if s.count(i)!=1: continue else: list1.append(i) if len(list1)==s1 or len(list1)==0: return -1 else: for j in list1: list2.append(s.index(j)) a=sorted(list2) return a[0] else: return -1
内容总结
以上是互联网集市为您收集整理的Leecode刷题之旅-C语言/python-387 字符串中的第一个唯一字符全部内容,希望文章能够帮你解决Leecode刷题之旅-C语言/python-387 字符串中的第一个唯一字符所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。