u/Owoc - 2 Archived Voat Posts in v/programming
u/Owoc
  • home
  • search

u/Owoc

0 posts · 2 comments · 2 total

Active in: v/programming (2)

  • ‹‹‹
  • ‹‹
  • ‹
  • 1
  • ›
  • ››
  • ›››
Comment on: We need more programming challenges. We should start off small: First non-repeating character of a string. Any language you like.

It could alternatively be written like MrKequc's snippet to be much more concise, but slower:

public static char firstNonRepeatingCharacter (String s) {
    for (char c : s.toCharArray()) {
        if (s.indexOf(c) == s.lastIndexOf(c)) {
            return c;
        }
    }
    throw new IllegalArgumentException();
}
2 16 Apr 2016 13:21 u/Owoc in v/programming
Comment on: We need more programming challenges. We should start off small: First non-repeating character of a string. Any language you like.

Java:

public static char findFirstNonRepeatingCharacter(String s) {
    if (s.isEmpty()) {
        throw new IllegalArgumentException();
    }
    LinkedHashMap<Character, Integer> occurrences = new LinkedHashMap<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (occurrences.containsKey(c)) {
            occurrences.put(c, occurrences.get(c) + 1);
        } else {
            occurrences.put(c, 1);
        }
    }
    for (Character c : occurrences.keySet()) {
        if (occurrences.get(c) == 1) {
            return c.charValue();
        }
    }
    throw new RuntimeException();
}
1 15 Apr 2016 13:15 u/Owoc in v/programming
  • ‹‹‹
  • ‹‹
  • ‹
  • 1
  • ›
  • ››
  • ›››

archive has 9,592 posts and 65,719 comments. source code.