LeetCode之First Unique Character in a String

简介: LeetCode之First Unique Character in a String

1、题目

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.


2、代码实现

public class Solution {

   public int firstUniqChar(String s) {

 if (s == null || s.length() == 0) {

  return -1;

 }

 HashMap<Character, Integer> map = new HashMap<Character, Integer>();

 for (int i = 0; i < s.length(); i++) {

  Integer in = map.get(s.charAt(i));

  if (in == null)

   map.put(s.charAt(i), 1);

  else

   map.put(s.charAt(i), 2);

 }

 for (int i = 0; i < s.length(); i++) {

  if(map.get(s.charAt(i)) == 2) {

   continue;

  } else {

   if (map.get(s.charAt(i)) == 1) {

    return i;

   }

  }

 }

 return -1;

}

}


3、总结

一般看到求数组里面唯一元素,和字符串里面唯一元素,我们可以通过HashMap来解决,每个字符或者元素作为key,然后出现一次设置一个value1,出现2次以上设置一个统一的value2,最后通过遍历得到value1,来解决问题


相关文章
|
4月前
|
JSON Java 关系型数据库
Java更新数据库报错:Data truncation: Cannot create a JSON value from a string with CHARACTER SET 'binary'.
在Java中,使用mybatis-plus更新实体类对象到mysql,其中一个字段对应数据库中json数据类型,更新时报错:Data truncation: Cannot create a JSON value from a string with CHARACTER SET 'binary'.
483 4
Java更新数据库报错:Data truncation: Cannot create a JSON value from a string with CHARACTER SET 'binary'.
|
索引
LeetCode 387. First Unique Character in a String
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
139 0
LeetCode 387. First Unique Character in a String
|
存储 算法 Java
First Unique Character in a String (找到一个字符串中第一个不重复的字符)
针对给定的一个字符串 s,你需要写一个算法,返回给定字符串中不重复字符的位置(index),如果所有的字符在给定的字符串中都有重复的话,那么你应该返回 -1。
352 0
LeetCode之First Unique Character in a String
LeetCode之First Unique Character in a String
129 0
|
Java 索引 Python
LeetCode 387: 字符串中的第一个唯一字符 First Unique Character in a String
题目: 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。
794 0
[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. Not
1190 0