《剑指offer》—— 50 第一个只出现一次的字符
程序员文章站
2022-07-10 13:35:16
...
题目
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路
- 利用HashMap(存储时不按顺序,找第一个不重复的字符时如果要遍历hashmap可以用LinkedHashMap;或者遍历原字符串)。
代码
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str.length() <= 0) return -1;
char[] ch = str.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
int index = 0;
for(int i = 0; i < ch.length; i++){
if(!map.containsKey(ch[i])){
map.put(ch[i],1);
}
else{
int count = map.get(ch[i]);
map.put(ch[i],++count);
}
}
//按顺序遍历字符数组,返回第一个hashmap中value=1的
for(int i = 0; i < ch.length; i++){
if(map.get(ch[i]) == 1)
return i;
}
return -1;
}
}
推荐阅读
-
在字符串中找出第一个只出现一次的字符。经典C语言例题
-
剑指offer JZ54 字符流中第一个不重复的字符 Python 多解
-
数据结构算法(第一个只出现一次的字符位置)
-
剑指 offer代码最优解析——面试题35第一个只出现一次的字符
-
【剑指offer】面试题56(1):数组中只出现一次的两个数字
-
剑指offer:数组中只出现一次的两个数字(java版)
-
剑指offer 面试题56 python版+解析:数组中只出现一次的两个数字,数组中唯一只出现一次的数字
-
剑指offer第二版-56.数组中只出现一次的两个数字
-
【算法分享】剑指offer56-数组中只出现一次的两个数字
-
剑指 Offer 56 - I. 数组中只出现一次的两个数字