(UVA) Pesky Palindromes - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=289
The solution below checks all the possible palindrome present in a given word, and it also checks if that palindrome was already considered.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while (line != null) {
HashSet<String> palindromes = new HashSet<>();
for (int i = 0; i < line.length(); i++) {
for (int j = i; j < line.length(); j++) {
String word = line.substring(i, j+1);
boolean palindrome = true;
for (int k = 0, l = word.length()-1; k < l; k++, l--) {
if (word.charAt(k) != word.charAt(l)) {
palindrome = false;
break;
}
}
if (palindrome) {
palindromes.add(word); // only add if it is a new word
}
}
}
System.out.println("The string '" + line + "' contains " + palindromes.size() + " palindromes.");
line = br.readLine();
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below checks all the possible palindrome present in a given word, and it also checks if that palindrome was already considered.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while (line != null) {
HashSet<String> palindromes = new HashSet<>();
for (int i = 0; i < line.length(); i++) {
for (int j = i; j < line.length(); j++) {
String word = line.substring(i, j+1);
boolean palindrome = true;
for (int k = 0, l = word.length()-1; k < l; k++, l--) {
if (word.charAt(k) != word.charAt(l)) {
palindrome = false;
break;
}
}
if (palindrome) {
palindromes.add(word); // only add if it is a new word
}
}
}
System.out.println("The string '" + line + "' contains " + palindromes.size() + " palindromes.");
line = br.readLine();
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment