记录一道面试题
- 1.给定一个由26个字母随机组成的字符串,找出其中第一个不重复的字母;
- 2.思路:由于字符串由26个字母组成,所以可以定义一个长度为26的记录数组arrays, arrays[0]记录字符串中‘a’的个数,
- arrays[1]记录字符串中‘b’的个数,以此类推。遍历字符串,在相应记录数组位置+1;
- 3.由于题目要求是给出第一个不重复的字母,所以在统计完字母个数后,需要重新遍历字符串,找出第一个不重复字母。
- 4.下面是用 Java 实现的代码:
1 package Algorithm; 2 3 public class GetFirstSingleLitter { 4 5 /** 6 * 给定一个由26个字母随机组成的字符串,找出其中 7 * 第一个不重复的字母,并输出。 8 * @param ch 9 * @return 10 */ 11 public static int getFirstSingleLitter(char[] ch) { 12 int[] arrays = new int[26]; // 记录数组,下标 0-25 分别对应字母表中的 a-z,用于记录字符串中对应字符出现的次数 13 for(int i = 0; i < 26; i ++) { 14 arrays[i] = 0; 15 } 16 for(int i = 0; i < ch.length; i ++) { 17 arrays[ ch[i] - 97 ] ++; // a 的 ASCII 码为 97, a 对应记录数组中的 arrays[0] 18 } 19 int index = 0; 20 int i = 0; 21 for(; i < ch.length; i ++) { 22 int loc = ch[i] - 97; // 该字母在记录数组中的位置 23 if(arrays[loc] != 1) 24 arrays[loc] = 0; 25 else { 26 index = i; 27 break; 28 } 29 } 30 if(i == ch.length) 31 return -1; 32 else 33 return index; 34 } 35 36 public static void main(String[] args) { 37 String str = "aabbccsadefaas".toLowerCase(); 38 char[] ch = str.toCharArray(); 39 int index = getFirstSingleLitter(ch); 40 if(index == -1) 41 System.out.println("没有不重复字母"); 42 else 43 System.out.println("第一个不重复的字母 : " + ch[index]); 44 } 45 }
注:这类问题对于思路的转变,思维的锻炼有一个较好的作用,可多学多做多看。