第17题:返回字符串中第一个只出现一次的字符


欢迎转载,转载请务必注明出处:http://blog.csdn.net/alading2009/article/details/45193239


第17题:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。

这题解法确实很巧妙,看了答案,发现有一点小问题。文档整理的答案中,在记录了字符串中各字符出现的次数以后,接着是按ASCII码值从小到大来搜索大小为256的数组,这样返回的是出现次数为1且ASCII码值最小的字符。假如有一串字符:“akab”,按文档所给算法,那么返回的是将是b,而不是第一个出现的k,因为b的ASCII码值比k小,在数组中将先于k被搜索到。


代码

package test017;

/**
 * Created by cq on 2015/4/21.
 * 定义一个新类型
 */
public class SpecifiedInteger {
    //字符出现的次数
    private int freq;
    //字符在字符串中最后出现的位置
    private int index;

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public int getFreq() {
        return freq;
    }

    public void setFreq(int freq) {
        this.freq = freq;
    }

}
package test017;

/**
 * Created by cq on 2015/4/21.
 * 第17题:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。
 */
public class Test017 {
    public static void getFirstAppearOnceChar(String s){
        if (s == null){
            return;
        }

        //假设字符编码为ASCII,则总共只有256个
        SpecifiedInteger[] temp = new SpecifiedInteger[256];
        for (int i = 0; i < 256; i++){
            temp[i] = new SpecifiedInteger();
        }

        char[] charArray = s.trim().toCharArray();
        int index = 0;

        //记录字符串中每个字符出现的次数
        for (char c:charArray){
            temp[c].setFreq(temp[c].getFreq()+1);
            temp[c].setIndex(index++);
        }

        //firstSingleChar赋初值为字符串的第一个字符,若第一个字符不只出现一次,则将其位置信息标为MAX_VALUE
        int firstSingleChar = charArray[0];
        if (temp[firstSingleChar].getFreq() != 1){
            temp[firstSingleChar].setIndex(Integer.MAX_VALUE);
        }
        //遍历256个位置,搜索第一个只出现一次的字符
        for (int i = 0; i < 256; i++){
            if (temp[i].getFreq() == 1 && temp[i].getIndex() < temp[firstSingleChar].getIndex()){
                firstSingleChar = i;
            }
        }

        System.out.println((char)firstSingleChar);
    }
    public static void main(String[] args){
        getFirstAppearOnceChar("adkffagddk");

        getFirstAppearOnceChar("abaccdeff");


    }
}




执行结果

Connected to the target VM, address: '127.0.0.1:2755', transport: 'socket'
g
b
Disconnected from the target VM, address: '127.0.0.1:2755', transport: 'socket'

Process finished with exit code 0


所有代码均已上传到GitHub,传送门

版权所有,转载请注明出处 http://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/
原文地址:https://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/p/12041979.html