OctA
BAN USER- 0of 0 votes
AnswersGiven a string, parse it and return a string array. It's like a tokenizer, but the rules are too...
- OctA in United States
For exmple, string="abc(edf)hij{klmn}opq[rst]uvw"
The delimiter are (), {}, []. They are in pair. So output array:
["abc", "edf", "hij", "klmn", "opq", "rst", "uvw"]
That's the rule 1. The rule 2 is, if any two consecutive "(" means escaping, that is "((" is actually output char "(". It's not part of the delimitor. Similar to ")", "{", "}", "[", "]".
abc(e))df) => ["abc", "e)df"], since the "))" outpus ")".
Rule 3: if "{" is inside a delimiter pair (), then "{" isn't part of the delimitor. Output it as is.
abc(e{df}}g) => ["abc", "e{df}}g"]| Report Duplicate | Flag | PURGE
HULU Software Engineer Algorithm
public static String[] extractSubstrings(String str) {
ArrayList<String> list = new ArrayList<String>();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '(' || c == ')') {
if (c == '(' && str.charAt(i+1) == '(') {
buffer.append(String.valueOf(c));
i++;
} else if (c == ')' && i + 1 < str.length() && str.charAt(i+1) == ')') {
buffer.append(String.valueOf(c));
i++;
} else if (buffer.length() > 0) {
list.add(buffer.toString());
buffer = new StringBuffer();
}
} else if (c == '{' || c == '}') {
if (c == '{' && str.charAt(i+1) == '{') {
buffer.append(String.valueOf(c));
i++;
} else if (c == '}' && i + 1 < str.length() && str.charAt(i+1) == '}') {
buffer.append(String.valueOf(c));
i++;
} else if (buffer.length() > 0) {
list.add(buffer.toString());
buffer = new StringBuffer();
}
} else if (c == '[' || c == ']') {
if (c == '[' && str.charAt(i+1) == '[') {
buffer.append(String.valueOf(c));
i++;
} else if (c == ']' && i + 1 < str.length() && str.charAt(i+1) == ']') {
buffer.append(String.valueOf(c));
i++;
} else if (buffer.length() > 0) {
list.add(buffer.toString());
buffer = new StringBuffer();
}
} else {
buffer.append(String.valueOf(c));
}
}
if (buffer.length() > 0) {
list.add(buffer.toString());
}
return list.toArray(new String[0]);
}
Better way?
- OctA October 29, 2016
If all values are positive integers then we can do this
- OctA November 09, 2016