LeetCode之First Unique Character in a String
发布日期:2021-06-29 14:08:02 浏览次数:2 分类:技术文章

本文共 824 字,大约阅读时间需要 2 分钟。

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
map = new HashMap
(); 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,来解决问题
 

转载地址:https://chenyu.blog.csdn.net/article/details/67725141 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode之Find the Difference
下一篇:LeetCode之First Unique Character in a String

发表评论

最新留言

不错!
[***.144.177.141]2024年04月16日 04时27分18秒