zoukankan      html  css  js  c++  java
  • [LeetCode]387.First Unique Character in a String

    题目描述:

    Given a string, find the first non-repeating character in it and return it's index.
    If it doesn't exist, return -1.

    Examples:
    s = "leetcode"
    return 0.

    s = "loveleetcode",
    return 2.
    Note: You may assume the string contain only lowercase letters.

    思路:

    给定一个字符串,找出第一个非重复出现的字符所在的位置。如果不存在则返回-1。
    假设字符串只包含小写字母。
    思路:
    将s的所有字符存入一个hashmap,map<K,V> K 指字符,V指出现的次数。存入时每个字符依次判断是否在map中存在。
    如果K存在,则map的V值+1
    最后从0开始遍历map,判断第一次出现V的值等于1的即返回i

     1 public class Solution387 {
     2     public int firstUniqChar(String s) {
     3         if(s.length()==0||s==null){return -1;}
     4         HashMap<Character, Integer> map = new HashMap<>();
     5         char[] ch = s.toCharArray();
     6         for(int i = 0; i < s.length();i++){
     7             if(map.containsKey(ch[i])) map.put(ch[i], map.get(ch[i])+1);
     8             else {
     9                 map.put(ch[i], 1);
    10             }
    11         }
    12         for(int i = 0; i < s.length();i++){
    13             if(map.get(ch[i])==1){
    14                 return i;
    15             }
    16         }
    17         return -1;
    18     }
    19     public static void main(String[] args) {
    20         // TODO Auto-generated method stub
    21         Solution387 solution387 = new Solution387();
    22         String s = "loveleetcode";
    23         System.out.println(solution387.firstUniqChar(s));
    24     }
    25 
    26 }
  • 相关阅读:
    第九章、查找
    opencv- python使用
    opencv初入
    初入
    第四章、数学问题
    数据结构
    分享一个SQLSERVER脚本
    详解SQL语句的集合运算
    数据库权限分配探讨
    数据库分区分表以及读写分离
  • 原文地址:https://www.cnblogs.com/zlz099/p/8252017.html
Copyright © 2011-2022 走看看