Created
May 28, 2014 03:17
-
-
Save adohe-zz/bcfb731ef8606d3c980d to your computer and use it in GitHub Desktop.
Find the first non-repeating character within the string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.westudio.java; | |
| import java.util.*; | |
| /** | |
| * Created with IntelliJ IDEA. | |
| * User: tonyhe | |
| * Date: 14-5-28 | |
| * Time: 上午10:56 | |
| * To change this template use File | Settings | File Templates. | |
| */ | |
| public class Programming { | |
| public static char getFirstNonRepeatedChar(String str) { | |
| Map<Character, Integer> counts = new LinkedHashMap<Character, Integer>(str.length()); | |
| for (char c : str.toCharArray()) { | |
| counts.put(c, counts.containsKey(c) ? counts.get(c) + 1 : 1); | |
| } | |
| for (Map.Entry<Character, Integer> entry : counts.entrySet()) { | |
| if (entry.getValue() == 1) { | |
| return entry.getKey(); | |
| } | |
| } | |
| throw new RuntimeException("can't find any non repeated character"); | |
| } | |
| public static char firstNonRepeatedChar(String str) { | |
| Set<Character> repeating = new HashSet<Character>(); | |
| List<Character> noRepeating = new ArrayList<Character>(); | |
| for (int i = 0; i < str.length(); i++) { | |
| char c = str.charAt(i); | |
| if (repeating.contains(c)) { | |
| continue; | |
| } | |
| if (noRepeating.contains(c)) { | |
| noRepeating.remove(noRepeating.indexOf(c)); | |
| repeating.add(c); | |
| } else { | |
| noRepeating.add(c); | |
| } | |
| } | |
| return noRepeating.get(0); | |
| } | |
| public static char firstNonRepeatingChar(String str) { | |
| HashMap<Character, Integer> counts = new HashMap<Character, Integer>(); | |
| for (int i = 0; i < str.length(); i++) { | |
| char c = str.charAt(i); | |
| if (counts.containsKey(c)) { | |
| counts.put(c, counts.get(c) + 1); | |
| } else { | |
| counts.put(c, 1); | |
| } | |
| } | |
| for (int j = 0; j < str.length(); j++) { | |
| char c = str.charAt(j); | |
| if (counts.get(c) == 1) { | |
| return c; | |
| } | |
| } | |
| throw new RuntimeException("can't find any non repeated character"); | |
| } | |
| public static void main(String[] args) { | |
| System.out.println(Programming.getFirstNonRepeatedChar("hello")); | |
| System.out.println(Programming.firstNonRepeatedChar("Swiss")); | |
| System.out.println(Programming.firstNonRepeatingChar("aabcdcdbe")); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment