第一个只出现一次的字符

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
 
第一种方法:
利用ASCII码用字符作为数组的下标索引存储,字符出现的次数即是对应索引的值,俩次循环,时间复杂度为O(n),最后做个判断即可。
 1 public class Solution {
 2     public int FirstNotRepeatingChar(String str) {
 3         char[] c = str.toCharArray();
 4         int[] a = new int[123];  //注意这里不能填122,会数组越界,加1即可
 5         for (char d : c) // 即遍历字符数组c的每一个字符,并将它以ASCII码作为下标存储到整型数组中
 6             a[(int) d]++;
 7         for (int i = 0; i < c.length; i++)
 8             if (a[(int) c[i]] == 1)
 9                 return i;   //从字符数组找到第一个只出现一次的字符,并返回它的位置
10         return -1;
11     }
12 
13     public static void main(String[] args) {
14         String abs = "NXWtnzyoHoBhUJaPauJaAitLWNMlkKwDYbbigdMMaYfkVPhGZcrEwpv";
15         Solution solution = new Solution();
16         int p = solution.FirstNotRepeatingChar(abs);
17         System.out.println(p);
18 
19     }
20 }

 

 

第二种方法:

使用HashMap映射的性质来求解问题

 1 import java.util.HashMap;
 2 
 3 public class Solution {
 4     public int FirstNotRepeatingChar(String str) {
 5         HashMap <Character, Integer> map = new HashMap<Character, Integer>();
 6         for(int i=0;i<str.length();i++){
 7             if(map.containsKey(str.charAt(i))){
 8                 int time = map.get(str.charAt(i));
 9                 map.put(str.charAt(i), ++time);
10             }
11             else {
12                 map.put(str.charAt(i), 1);
13             }
14         }
15         int pos = -1;  
16         int i=0;
17         for(;i<str.length();i++){
18             char c = str.charAt(i);
19             if (map.get(c) == 1) {
20                 return i;
21             }
22         }
23         return pos;
24     }
25 }

 

posted @ 2018-08-18 09:55  Octopus22  阅读(85)  评论(0编辑  收藏  举报