您的位置:首页 > Web前端

剑指Offer------第一个只出现一次的字符

2017-10-05 12:18 302 查看

题目描述

在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置

<分析>
采用散列表 --HashMap存储字符和出现的次数

import java.util.HashMap;

/**
*
* @author zy
* @date 2017年10月5日 上午11:29:49
* @Decription 在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
*/
public class Ex23 {
public int FirstNotRepeatingChar(String str) {
HashMap<Character, Integer> hashMap = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
if (hashMap.containsKey(str.charAt(i))) {
int time = hashMap.get(str.charAt(i));
hashMap.put(str.charAt(i), ++time);
}else {
hashMap.put(str.charAt(i),1);
}
}
for (int i = 0; i < str.length(); i++) {
if (hashMap.get(str.charAt(i))==1) {
return i;
}
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: