面试题50:第一次只出现一次的字符

/*

 * 面试题50:第一次只出现一次的字符

 * 题目:在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1.

 * 思路:定义哈希表,键值是字符,值是该字符出现的次数。从头开始扫描字符串2次:

 * 第一次:每扫描到一个字符,就在哈希表的对应项中把次数加1

 * 第二次:每扫描到一个字符,就能从哈希表中得到该字符出现的次数。

 *

 */

 

import java.util.LinkedHashMap;

 

public class No50FirstNotRepeatingChar {

 

    public static void main(String[] args) {

       No50FirstNotRepeatingChar n = new No50FirstNotRepeatingChar();

       String str = "dfftyghjkddd";

       System.out.println(n.FirstNotRepeatingChar(str));

    }

 

    public int FirstNotRepeatingChar(String str) {

       if (str == null || str.length() == 0) {

           return -1;

       }

      

       char[] c = str.toCharArray();

       LinkedHashMap<Character , Integer> hash = new LinkedHashMap<Character, Integer>();

       //第一次:每扫描到一个字符,就在哈希表的对应项中把次数加1

       for (char item : c) {

           if(hash.containsKey(item))

              hash.put(item, hash.get(item) + 1);

           else

              hash.put(item, 1);

       }

       //第二次:每扫描到一个字符,就能从哈希表中得到该字符出现的次数。

       for(int i = 0; i < str.length(); i++) {

           if(hash.get(str.charAt(i)) == 1) {

              return i;

           }

       }

       return -1;

    }

 

}

猜你喜欢

转载自blog.csdn.net/juaner1993/article/details/82760399