caleb.cittadino
BAN USERAssuming you are allowed to keep track of a list of each character's positions while the string is built, then the best and average case of 'replaceChar()' would be < O(n). What do you guys think?
import java.util.*;
public class HelloWorld {
static Map<Character, List<Integer>> positions = new HashMap<Character, List<Integer>>();
public static void main(String []args) {
String s = buildString('h','e','l','l','o',' ','w','o','r','l','d');
System.out.println("s: " + s);
System.out.println(positions);
s = replaceChar(s, 'l', 'X');
System.out.println("s: " + s);
}
static String buildString(char... chars) {
String s = null;
for (char c : chars) {
s = append(s, c);
}
return s;
}
static String append(String s, char c) {
if (s == null) s = "";
String newS = s + c;
List<Integer> charPositions = positions.get(c);
if (charPositions == null) {
charPositions = new ArrayList<Integer>();
positions.put(c, charPositions);
}
charPositions.add(newS.length()-1);
return newS;
}
static String replaceChar(String s, char c, char newC) {
List<Integer> charPositions = positions.get(c);
if (charPositions == null) return s;
char[] charArr = s.toCharArray();
for (int pos : charPositions) {
charArr[pos] = newC;
}
return new String(charArr);
}
}
Output is:
s: hello world
{w=[6], d=[10], =[5], e=[1], r=[8], o=[4, 7], l=[2, 3, 9], h=[0]}
s: heXXo worXd
I chose to map from the key to a list of ordered values (for collisions):
Output is:
This solution handles all of the corner cases I could think of:
- caleb.cittadino April 24, 20141) Null fileName
2) Empty fileName
3) fileName with missing extension
4) fileName with no underscores
5) fileName with underscores, without key-value-pairs
6) fileName with underscores, with 1 or more key-emptyValue-pairs
What do you guys think? Any better way to parse this? Any corner cases I missed?