Friday, December 14, 2012

SRM 564 div 2 250-pt

Problem
http://community.topcoder.com/stat?c=problem_statement&pm=12325 

Approach
Create two new strings:
1. reverse = append new chars to the front
2. faux = only add chars if it's different from the previous one

Looking at the documentation for appending chars to Strings in Java i relized i should be using the StringBuffer class, and then I found the reverse() function, which meant I didn't need to build the reverse string, just use the reverse() method.

So my approach was correct, I just didn't know about reverse() and didn't think to use StringBuffer right away, so I need to get more familiar with Java.


Code
public class FauxPalindromes
{
public String classifyIt(String word)
{
StringBuffer reverse = new StringBuffer(word);
reverse.reverse();
if (reverse.toString().equals(word))
return "PALINDROME";

char lastChar = word.charAt(0);
StringBuffer faux = new StringBuffer();
faux.append(lastChar);

for (int i = 1; i < word.length(); i++)
{
if (word.charAt(i) != lastChar)
{
lastChar = word.charAt(i);
faux.append(lastChar);
}
}
reverse = new StringBuffer(faux.toString());
reverse.reverse();

if (reverse.toString().equals(faux.toString()))
return "FAUX";

return "NOT EVEN FAUX";
}
}

No comments:

Post a Comment

There was an error in this gadget