zoukankan      html  css  js  c++  java
  • 初级算法-14. 字符串中的第一个唯一字符

    题目描述:

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

    示例:
    s = "leetcode"
    返回 0.
    
    s = "loveleetcode",
    返回 2.

    分析:遍历字符串,当字符第一次出现时,用lastIndexOf()判断是否是最后一个,是就返回其下标,第一次出现add 进HashSet,再次出现就会add失败

     1 class Solution {
     2     public int firstUniqChar(String s) {
     3         HashSet<Character> set=new HashSet<>();
     4      for(int i=0;i<s.length();i++){
     5          char t=s.charAt(i);
     6          if( set.add(t)&&s.lastIndexOf(t)==i)return i;//第一次出现且是最后一个
     7      }      return -1;
     8     }
     9     
    10 }

    上面的算法比较简单,但是效率不行,用了28ms

    下面是运行2ms的代码,思想是遍历每个字母,判断它第一次出现的位置和最后一次出现的位置,若相等则代表只出现过一次,然后返回只出现一次中最先出现的(下标最小)

     1 class Solution {
     2     public int firstUniqChar(String s) {
     3         int result = -1;
     4         for(char i = 'a'; i <= 'z'; i++){
     5             int first = s.indexOf(i);
     6             if(first!=-1){//存在
     7                 if(first == s.lastIndexOf(i)){//只出现一次
     8                  //只出现一次中最先出现的
     9                 result = result==-1?first:Math.min(result, first);
    10                 }
    11             }
    12         }
    13         return result;
    14     }
    15 }        
  • 相关阅读:
    python 函数的进阶
    python 函数的基础
    python3.6 中特殊格式化 和 字典中的pop
    python 文件操作
    python 基础数据类型补充,set集合,深浅拷贝
    python is 和 == 的区别,编码问题
    python字典
    python中堆和栈_Python小知识00002
    pip的更新_Python小知识00001
    Python字符串的编码
  • 原文地址:https://www.cnblogs.com/hzhqiang/p/10841333.html
Copyright © 2011-2022 走看看