【题目】在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符的位置。
* 若为空串,返回-1。位置索引从0开始
* 【思路】1 首先遍历字符串数组,添加字符和对应出现的次数,可以用HashMap(字符,对应出现的次数)来实现。
* 2 再遍历数组,当遍历到字符出现次数为1的时候,输出。
1 package com.exe11.offer; 2 import java.util.HashMap; 3 import java.util.Map; 4 /** 5 * 【题目】在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符的位置。 6 * 若为空串,返回-1。位置索引从0开始 7 * 【思路】1 首先遍历字符串数组,添加字符和对应出现的次数,可以用HashMap(字符,对应出现的次数)来实现。 8 * 2 再遍历数组,当遍历到字符出现次数为1的时候,输出。 9 * @author WGS 10 * 11 */ 12 13 public class FirstNoRepeatingChar { 14 15 16 public char firstNoRepeatingChar(String str){ 17 if(str==null ||str.equals("")) 18 return ' '; 19 char[] ch=str.toCharArray(); 20 Map<Character,Integer> map=new HashMap<Character,Integer>(); 21 //1 遍历数组,添加字符串每个字符及字符对应的次数。首次出现设置次数为1,如果有就在原有次数上+1 22 for(char c:ch){ 23 if(map.get(c)!=null){//map.get(c):看集合中字符(key)对应的次数(value)是否为0(null) 24 map.put(c, map.get(c)+1);//map.get(c)+1:字符c对应的次数不为0,即字符串中已有字符c,就在原有次数上+1 25 }else{ 26 map.put(c, 1);//如果集合中没有c字符,就为第一次添加,次数设置为1 27 } 28 } 29 //2 重新遍历数组,获取第一个次数为1 的字符 30 for(int i=0;i<ch.length;i++){ 31 if(map.get(ch[i])==1) 32 return ch[i];// 返回首次出现的字符 33 } 34 return 0; 35 36 } 37 public static void main(String[] args) { 38 FirstNoRepeatingChar f=new FirstNoRepeatingChar(); 39 //String str="abcdef"; 40 //String str="abacdef"; 41 //String str="abcdefabf"; 42 String str="aabb"; 43 char c=f.firstNoRepeatingChar(str); 44 System.out.println(c); 45 46 47 } 48 49 }