Problem description
Finds the first occurrence of a character in a string. If the input string "ABBC", the character ' a ' should be output.
Program
public class Firstcharacter {//Time/space:o (n) public Char Findfirstappearchar (String s) {if (s = = NULL | | s.length () = = 0) {return ';} Hashmap<character, integer> map = new Hashmap<character, integer> (); for (int i = 0; i < s.length (); i++) {C Har C = S.charat (i), if (!map.containskey (c)) {Map.put (c, 1),} else {map.put (c, Map.get (c) + 1);}} for (int i = 0; i < s.length (); i++) {char c = s.charat (i); if (Map.get (c) = = 1) {return c;}} Return ';} Time:o (n^2) public Char findfirstappearcharnaive (String s) {if (s = = NULL | | s.length () = = 0) {return ';} for (int i = 0; i < s.length (); i++) {char c = s.charat (i); Boolean flag = true;for (int j = i + 1; j < S.length (); j + +) {if (S.charat (j) = = c) {flag = False;break;}} if (flag) {return c;}} Return ';}}
Solution 17: Characters that appear only once in a string