题目:在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出‘b’。

代码实现:

import java.util.HashMap;

public class Solution{
     public static char firstNotRepeatingChar(String s){
          if(s==null||s.length()==0){
                return ' ';
          }
          char[] chArray=s.toCharArray();
          HashMap<Character,Integer> map=new HashMap<>();
          for(int i=0;i<chArray.length;i++){
                char c=chArray[i];
                if(map.containsKey(c)){
                        map.put(c,-1);
                }else{
                        map.put(c,1);
                }
          }
          char result=' ';
          for(Object key:map.keySet()){
                 int value=(int)map.get(key);
                 if(value!=-1){
                         result=(char)key;
                         break;
                 }
           }
                 return result;
     }

     public static void main(String[] args){
            String s="abaccdeff";
            char c=firstNotRepeatingChar(s);
            if(c==' '){
                  System.out.println("Not exist!");
            }else{
                  System.out.println(c);
            }
     }
}

 

 posted on 2018-11-22 19:18  会飞的金鱼  阅读(111)  评论(0)    收藏  举报