在一个字符串中找到第一个只出现一次的字符
问题:
给定一个字符串,比如 A = “ABCDACD”, 找出第一个只出现一次的字符,在A中,第一个只出现一次的字符是‘B’。
分析:
为了判定某字符是否出现一次,我们可以从从头开始往下遍历,如果没有重复,则选取,否则抛弃。这样做的话复杂度为 O(n^2)。其实,对于判定是否存在或者存在的次数等问题,基本上都会与hastable有关,我们可以构建一个数组 array[256] (ASCII), 然后对字符串先进行处理,对于每个出现的字符,我们可以在相对应的位置+1。这样,我们再次从头开始对字符串进行遍历,如果发现某一字符个数为1,则返回该字符。
代码如下:
1 //if there is no such character in A, return -1 (null) 2 public char firstOnlyCharacter(String A) { 3 int[] array = new int[256]; 4 5 //store the characters in A to array 6 for (int i = 0; i < A.length(); i++) { 7 array[A.charAt(i)] += 1; 8 } 9 10 //get the first charater with only one appearance in A 11 for (int i = 0; i < A.length(); i++) { 12 if (array[A.charAt(i)] == 1) return A.charAt(i); 13 } 14 return -1; 15 }
转载请注明出处。

浙公网安备 33010602011771号