java - All combinations of alphanumeric string, better way? -
the input "alphanumeric" function string consists of alphanumeric characters lower case, example "hello123hello". want able check upper/lower case letter combinations string through check( ) function. (eg. hello123hello 1 of combinations checked). have written code in java store matching string arraylist, know if there better way without arraylist. also, correct in saying worst case runtime of o(2^n)? note: check function returns either true or false, depending on whether correct string passed function.
public static string alphanumeric(string input) { arraylist<string> list = new arraylist<string>(); alphahelper(input, "", list); return list.get(0); } private static void alphahelper(string in, string current, arraylist<string> list) { if (in.length() == 0) { if (check(current)) { list.add(current); } } else if (character.isletter(in.charat(0))) { alphahelper(in.substring(1),current+in.substring(0,1).tolowercase(),list); alphahelper(in.substring(1),current+in.substring(0,1).touppercase(),list); } else if (character.isdigit(in.charat(0))) { alphahelper(in.substring(1),current+in.substring(0,1),list); } else { return; } }
if want remove arraylist
without changing basic algorithm, can this:
public static string alphanumeric(string input) { return alphahelper(input, ""); } private static string alphahelper(string in, string current) { string result = null; if (check(current)) { result = current; } else if (character.isletter(in.charat(0))) { result = alphahelper(in.substring(1),current+in.substring(0,1).tolowercase()); if (result == null) result = alphahelper(in.substring(1),current+in.substring(0,1).touppercase()); } else if (character.isdigit(in.charat(0))) { result = alphahelper(in.substring(1),current+in.substring(0,1)); } return result; }
yes o(2^n), , can't see offhand how improve on if can't original string directly.
if don't need check substrings (i.e. care case variations of entire string) improve algorithm not testing substrings, still o(2^n).
Comments
Post a Comment