美文网首页
【剑指Offer 35】第一个只出现一次的字符

【剑指Offer 35】第一个只出现一次的字符

作者: 3e1094b2ef7b | 来源:发表于2017-07-22 09:37 被阅读1次

题目:在字符串中找出第一个只出现一次的字符。

代码如下:

package demo;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 第1个只出现1次的字符
 * 
 * 记录法
 * 
 * @author xiangdonglee
 *
 */
public class Test35 {
    public static char firstNotRepeatingChar(String s) {
        if (s == null || s.length() < 1) {
            throw new IllegalArgumentException("Arg should not be null or empty!");
        }
        Map<Character, Integer> map = new LinkedHashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                map.put(c, -2);
            } else {
                map.put(c, i);
            }
        }
        Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
        // 记录只出现一次的字符的索引
        int index = Integer.MAX_VALUE;
        // 记录只出现一次的字符
        char result = '\0';
        for (Map.Entry<Character, Integer> entry : entrySet) {
            if (entry.getValue() >= 0 && entry.getValue() < index) {
                index = entry.getValue();
                result = entry.getKey();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println("google:" + firstNotRepeatingChar("google"));
        System.out.println("aabccdbd:" + firstNotRepeatingChar("aabccdbd:"));
        System.out.println("abcdefg:" + firstNotRepeatingChar("abcdefg"));
        System.out.println("gfedcba:" + firstNotRepeatingChar("gfedcba"));
        System.out.println("zgfedcba:" + firstNotRepeatingChar("zgfedcba"));
    }
}
运行结果

来源:http://blog.csdn.net/derrantcm/article/details/46761041

相关文章

网友评论

      本文标题:【剑指Offer 35】第一个只出现一次的字符

      本文链接:https://www.haomeiwen.com/subject/yfoykxtx.html