zoukankan      html  css  js  c++  java
  • Leecode刷题之旅-C语言/python-387 字符串中的第一个唯一字符

    /*
     * @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
  • 相关阅读:
    RabbitMQ简介、特性、使用场景、安装、启动与关闭
    mybatis的工作原理
    bzoj2119 股市的预测
    Noi2014 购票
    51Nod 算法马拉松22 开黑记
    COGS2485 从零开始的序列
    Codeforces Round #402 (Div.2)
    BestCoder Round #92
    COGS2294 释迦
    bzoj4764 弹飞大爷
  • 原文地址:https://www.cnblogs.com/lixiaoyao123/p/10564173.html
Copyright © 2011-2022 走看看