fsteeg.com | notes | tags

∞ /notes/abstraction | 2006-09-13 | algorithms programming

Abstraction

Cross-posted to: https://fsteeg.wordpress.com/2006/09/13/abstraction/

Say we want to remove all multiple consecutive letters by a single one, i.e. for an input like aaaccceeefff (lowercase, sorted) we want an output like acef. There are conceptually different approaches to such a problem:

RegEx-Solution:

String regexRes = input.replaceAll("([a-z])\\1+", "$1");

Data-Structure-Solution:

Set setRes = new TreeSet();
for (Character character : input.toCharArray()) {
 setRes.add(character);
}
StringBuilder builder = new StringBuilder();
for (Character character : setRes) {
 builder.append(character);
}
String dataRes = builder.toString();

Parser solution:

String compress(String input) {
 String res = "";
 for (int i = 0; i < input.length(); i++) {
  if (res.length() == 0
    || res.charAt(res.length() - 1) != input.charAt(i))
   res = res + input.charAt(i);
 }
 return res;
}