StringCoder
is #2 from the from the 2008 AP Computer Science A Free Response problems.
https://secure-media.collegeboard.org/apc/ap08_comp_sci_a_frq.pdf
Part (a) decodeString
method
public String decodeString(ArrayList<StringPart> parts)
{
String decoded = "";
for(StringPart sp : parts)
decoded += masterString.substring(
sp.getStart(), sp.getStart() + sp.getLength());
return decoded;
}
See more about manipulating Strings on the AP CS A Exam.
Part (b) encodeString
method
public ArrayList<StringPart> encodeString(String word)
{
ArrayList<StringPart> parts = new ArrayList<StringPart>();
String wordRemaining = word;
while(wordRemaining.length() > 0)
{
StringPart sp = findPart(wordRemaining);
parts.add(sp);
wordRemaining = wordRemaining.substring(sp.getLength());
}
return parts;
}
findPart
method (not required on Exam)
StringPart findPart(String str)
{
String strPart = str;
int index = masterString.indexOf(strPart);
while(index == -1)
{
strPart = strPart.substring(0, strPart.length() - 1);
index = masterString.indexOf(strPart);
}
return new StringPart(index, strPart.length());
}
This implementation finds the largest part of the beginning of str
that exists in masterString
.
2008 AP CS Exam Free Response Solutions
Help & comments
Get help from AP CS Tutor Brandon Horn