天地无极,乾坤剑法

导航

 

题目描述

找出字符串中第一个只出现一次的字符

 

 

 

 

输入描述:

输入一个非空字符串

输出描述:

输出第一个只出现一次的字符,如果不存在输出-1

示例1

输入

asdfasdfo

输出

o

代码如下:

 1 package com.yzh.hehe; 
 2 import java.util.LinkedList;
 3 import java.util.List;
 4 import java.util.Scanner;
 5 
 6 public class FindFirstOnlyOne {
 7 
 8     public static void main(String[] args) { 
 9         Scanner scanner=new Scanner(System.in);
10         while (scanner.hasNext()) {
11             System.out.println(findFirstOnlyOne(scanner.nextLine())); 
12         }
13         scanner.close(); 
14     }
15     //遍历string,当检查一个字符时已经存在不包含列表时,跳过处理以后字符,否则检查是否存在于包含列表中,
16     //如果存在就在不包含列表中添加此字符且在包含列表中删除此字符,如果不存在就添加在包含列表中的最后面。最后包含列表第一个就是结果字符。
17     private static Object findFirstOnlyOne(String string) {
18         if(string==null||"".equals(string)){
19             return -1;
20         }
21         List<Character>includeList=new LinkedList<Character>();//包含列表
22         List<Character>excludeList=new LinkedList<Character>();//不包含列表
23         for (int i=0;i<string.length(); i++) {
24             Character character =string.charAt(i);
25             if (!excludeList.contains(character)) {
26                 if (includeList.contains(character)) {
27                     excludeList.add(character);
28                     includeList.remove(character);
29                 }else {
30                     includeList.add(character);
31                 }
32             }
33         }
34         if (includeList.size()==0) {
35             return -1;
36         }
37         return includeList.get(0); 
38     }
39 }

 

posted on 2018-01-20 14:38  天地无极,乾坤剑法  阅读(150)  评论(0)    收藏  举报