题目描述
在一个字符串(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 HashMapmap = new HashMap (); 6 for(int i=0;i