Determining a Palindrome using Stack and Queue in java - java

Here I am trying to determine if a word or phrase is a palindrome by using stacks and queues depending on the phrase I write in.
What it is doing is that it says that everything is a palindrome and writes "Palindrome" by how many letters it has.
I'm guessing that I need to add something between the last for loop and the while loop, but I'm not sure what.
public class CheckPalindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = line.length() - 1; i >= 0; i--) {
queue.add(line.charAt(i));
}
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
}
}

I made some very minor modifications (first to fix one of your for loops, and second to prevent your "Palindrome/Not a Palindrome" message from printing once for every character in the input) to your code to get it to work:
import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
class Palindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = 0; i < line.length(); i++) {
queue.add(line.charAt(i));
}
boolean isPalindrome=true;
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
continue;
} else {
isPalindrome=false;
break;
}
}
if (!isPalindrome) {
System.out.println("Not a Palindrome");
} else {
System.out.println("Palindrome");
}
}
}
}

You need to put the characters into each of the stack and the queue in the same order. The point of using both is that one reverses the order and the other doesn't. Reversing the order yourself on one of them, as you are doing now, negates that.

Incase it's of interest, here's a variation on your approach using a Deque<E> as opposed to a Stack and Queue separately. A Deque is just a double ended queue (i.e. operates as both).
public static boolean isPalindrome(String word) {
boolean isPalindrome = word.length() == 1;
if (!isPalindrome) {
Deque<Character> wordDeque = new LinkedList<>();
for (Character c : word.toCharArray()) {
wordDeque.add(Character.toLowerCase(c));
}
isPalindrome = true;
while (isPalindrome && wordDeque.size() > 1) {
isPalindrome = wordDeque.pollFirst().compareTo(wordDeque.pollLast()) == 0;
}
}
return isPalindrome;
}

Here is new Solution. Try this one. If any modification ,let me know.
package Stack;
public class pallindrome {
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
void pushh(int new_Data) {
stack.push(new_Data);
}
void enquee(int new_Data) {
queue.add(new_Data);
}
int popStack(){
return stack.pop();
}
int dequeueQueue() {
return queue.remove();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();
// Convert input String to an array of characters:
char[] s = input.toCharArray();
// Create a Solution object:
pallindrome p = new pallindrome();
// Enqueue/Push all Integer to their respective data structures:
for(int i=0;i<input.length();i++)
{
p.pushh(i);
p.enquee(i);
}
// Pop/Dequeue the chars at the head of both data structures and compare them:
boolean isPalindrome = true;
for ( i = 0; i < s.length/2; i++) {
if (p.popStack() != p.dequeueQueue()) {
isPalindrome = false;
break;
}
}
//Finally, print whether string s is palindrome or not.
System.out.println( "The Integer, " + input + ", is "
+ ( (!isPalindrome) ? "not a palindrome." : "a palindrome." ) );
}
}

Using both stack and queue together for checking palindrome in JAVA
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the String:: ");
String real = input.nextLine();
Queue q = new LinkedList();
Stack st = new Stack();
for(int i=0; i<=real.length()-1; i++) {
q.add(real.charAt(i));
}
for(int i=0; i<real.length(); i++) {
st.push(real.charAt(i));
}
if(q.remove().equals(st.pop())) {
System.out.println("Palindrom");
}else {
System.out.println("Not Palindrom");
}
}
}

Related

Java--I get an infinite loop when attempting to run my alphabetizer program. I can't seem to find the error

The code runs correctly until the for-loops. That's really all to it; I just can't seem to figure out why I'm getting an infinite loop. I've just been trying to sort the word "May" and "Code", so it outputs [Code, May].
import java.util.*;
public class Alphabetical
{
public static void main(String[]args)
{
List<String>words = new ArrayList();
String word = "";
while(!word.equals("stop"))
{
Scanner s = new Scanner(System.in);
System.out.println("Enter a word. Enter 'stop' when finished.");
word = s.nextLine();
words.add(word);
}
words.remove(words.size()-1);
System.out.print(words);
String temp = "";
boolean breakthis = false ;
for(int i = words.size()-1; i >= 1;i--)
{
if(breakthis)
break;
temp = words.get(i);
for(int j = 0;j < words.size();i++)
{
if(temp.charAt(0) == words.get(j).charAt(0))
{
breakthis = true;
break;
}
if(temp.charAt(0) > words.get(j).charAt(0))
{
words.add(j, temp);
words.remove(words.size()-1);
i = words.size()-1;
break;
}
}
}
System.out.print(words);
}
}

Java: Print a unique character in a string

I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String[] args) {
String s="aabcddkkbghff";
String[] cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String[] args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int[] count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String [] str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"\t"+count);
}
}
public static void main(String [] args) {
uniqueValue(input);
}
Step1: To find the unique characters in a string, I have first taken the string from user.
Step2: Converted the input string to charArray using built in function in java.
Step3: Considered two HashSet (set1 for storing all characters even if it is getting repeated, set2 for storing only unique characters.
Step4 : Run for loop over the array and check that if particular character is not there in set1 then add it to both set1 and set2. if that particular character is already there in set1 then add it to set1 again but remove it from set2.( This else part is useful when particular character is getting repeated odd number of times).
Step5 : Now set2 will have only unique characters. Hence, just print that set2.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String str = input.next();
char arr[] = str.toCharArray();
HashSet<Character> set1=new HashSet<Character>();
HashSet<Character> set2=new HashSet<Character>();
for(char i:arr)
{
if(set1.contains(i))
{
set1.add(i);
set2.remove(i);
}
else
{
set1.add(i);
set2.add(i);
}
}
System.out.println(set2);
}
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char[] array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean[] uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
public class UniqueCharactersInString {
public static void main(String []args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int[] repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string. In the second line I am looking for characters repetitive once.
how about this :)
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
package extra;
public class TempClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
char[] myCharArray=abcString.toCharArray();
TempClass mClass=new TempClass();
mClass.countUnique(myCharArray);
mClass.countEach(myCharArray);
}
/**
* This is the program to find unique characters in array.
* #add This is nice.
* */
public void countUnique(char[] myCharArray) {
int arrayLength=myCharArray.length;
System.out.println("Array Length is: "+arrayLength);
char[] uniqueValues=new char[myCharArray.length];
int uniqueValueIndex=0;
int count=0;
for(int i=0;i<arrayLength;i++) {
for(int j=0;j<arrayLength;j++) {
if (myCharArray[i]==myCharArray[j] && i!=j) {
count=count+1;
}
}
if (count==0) {
uniqueValues[uniqueValueIndex]=myCharArray[i];
uniqueValueIndex=uniqueValueIndex+1;
count=0;
}
count=0;
}
for(char a:uniqueValues) {
System.out.println(a);
}
}
/**
* This is the program to find count each characters in array.
* #add This is nice.
* */
public void countEach(char[] myCharArray) {
}
}
Here str will be your string to find the unique characters.
function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
for(let j= 0; j< str.length; j++) {
if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
uniqueChars += str[i];
}
}
}
return uniqueChars;
}
public static void main(String[] args) {
String s = "aaabcdd";
char a[] = s.toCharArray();
List duplicates = new ArrayList();
List uniqueElements = new ArrayList();
for (int i = 0; i < a.length; i++) {
uniqueElements.add(a[i]);
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
duplicates.add(a[i]);
break;
}
}
}
uniqueElements.removeAll(duplicates);
System.out.println(uniqueElements);
System.out.println("First Unique : "+uniqueElements.get(0));
}
Output :
[b, c]
First Unique : b
import java.util.*;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
for(int i=0;i<test.length();i++){
if(test.lastIndexOf(test.charAt(i))!=i)
test=test.replaceAll(String.valueOf(test.charAt(i)),"");
}
System.out.println(test);
}
}
public class Program02
{
public static void main(String[] args)
{
String inputString = "abhilasha";
for (int i = 0; i < inputString.length(); i++)
{
for (int j = i + 1; j < inputString.length(); j++)
{
if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
{
inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
}
}
}
System.out.println(inputString);
}
}

How do I count each word in a file using Java

Im trying to write a program with three instance methods, but I cant seem to get it right. My method wordCount returns the number of lines in the file. Not the number of words as its supposed to.
Im just lost in the method mostFrequentWords..
Hope someone can help me out
package opgaver;
import java.util.*;
import java.io.*;
public class TextAnalysis14 {
Scanner file;
int CountWords = 0;
boolean Contains = true;
String[] words;
String[] MFwords;
public TextAnalysis14(String sourceFileName, int maxNoOfWords) {
String wordline;
words = new String[maxNoOfWords];
String[] line;
try {
file = new Scanner(new File(sourceFileName));
} catch (FileNotFoundException e) {
file = new Scanner("");
}
while (file.hasNext()) {
wordline = file.next();
line = wordline.split("[^a-zA -Z]+");
for (int i = 0; i < line.length; i++) {
if (!line[i].equals(" ")) {
words[CountWords] = line[i];
CountWords++;
}
}
}
if (words[CountWords] == (null)) {
for (int i = CountWords; i < maxNoOfWords; i++) {
words[i] = ("empty");
}
}
}
public int wordCount() {
return CountWords;
}
public boolean contains(String word) {
for (int i = 0; i < words.length; i++) {
if (words[i].contains(word)) {
return Contains;
}
}
return false;
}
public String[] mostFrequentWords() {
Arrays.sort(words);
return MFwords;
}
}
Because of my noob status I cannot make a comment but it looks like you have a space in your regex between A and -Z.
try with this.
public static void main(String[] args) {
String str = "this is a space String"; // read all lines in a file
String[] splited = str.split(" ");
List<String> list = new ArrayList<String>();
for(int i = 0;i < splited.length; i++){
if(splited[i].length() > 0){
list.add(splited[i]);
}
}
System.out.println(list.size());
}
by calling wordline = file.next(); you are not reading lines.
In TextAnalysis14 change your condition to file.hasNextLine() and read lines with file.nextLine()
while (file.hasNextLine()) {
wordline = file.nextLine();
....
}
You can try something like that using Java 8:
Stream<String> lines = Files.lines(Paths.get("c:/", "file.txt"));
in wordCount = lines.mapToInt(s -> s.split(' ').length()).sum();
This function just cound a words count in file.

find all palindromes in string

I need to find all the palindromes in a string. It takes user input
example: "abbaalla"
it loops through creating a substring that changes as the loop progresses.
example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..
once it reaches the max length of the word it iterates the start of the substring and repeats
example: check palindrome "b" "bb" "bba" and so on..
I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"
the final output should be a string that includes all palindromes. in this case;
output: "abba alla"
Also this program currently results in: String index out of range: -1
public static String findAllPalindromes(String input){
int indexStart = 0;
int wordMax = input.length();
int wordLength;
String checkPalindrome;
String allPalindromes = "";
for (wordLength = 2; wordLength <= wordMax; wordLength++) {
//creates a substring to check against isAllPalindrome method
checkPalindrome = input.substring(indexStart, wordLength);
//checks checkPalindrome string to see if it is a palindrome
if (isAllPalindrome(checkPalindrome) == true){
allPalindromes += " " + checkPalindrome;
if (checkPalindrome.length() >= allPalindromes.length()){
allPalindromes = checkPalindrome;
}
}
//once program reads string through once, increment index and scan text again
if (wordLength == wordMax && indexStart < wordMax){
indexStart++;
wordLength = 0;
}
}
System.out.println("The palindromes in the text are: ");
System.out.println(allPalindromes);
return allPalindromes;
}
public static Set<CharSequence> printAllPalindromes(String input) {
if (input.length() <= 2) {
return Collections.emptySet();
}
Set<CharSequence> out = new HashSet<CharSequence>();
int length = input.length();
for (int i = 1; i <= length; i++) {
for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
if (input.charAt(j) == input.charAt(k)) {
out.add(input.subSequence(j, k + 1));
} else {
break;
}
}
}
return out;
}
Simple Brute force way-->
public class AllPalindromes {
public static boolean checkPalindrome(String str) {
for(int i=0;i<=str.length()/2;i++)
if(str.charAt(i)!=str.charAt(str.length()-1-i))
return false;
return true;
}
public static void printAllPalindrome(String str) {
for(int i=0;i<=str.length();i++)
for(int j=i;j<str.length();j++)
if(checkPalindrome(str.substring(i,j+1)))
System.out.println(str.substring(i,j+1));
}
public static void main(String[] args) {
printAllPalindrome("abbaalla");
}
}
Here is the solution which displays all palindromes. (Only those palindromes which are of length greater than 3. You can change the if condition inside the loop if you want to print them all.)
Note that #jw23's solution does not display the palindromes which are of even length — only the odd length ones.
public class HelloWorld{
public static void printPalindromes(String s) {
if (s == null || s.length() < 3)
return;
System.out.println("Odd Length Palindromes:");
// Odd Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
System.out.println("\nEven Length Palindromes:");
// Even Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
}
public static void main(String[] args){
String s = "abcbaaabbaa";
printPalindromes(s);
}
}
public class Palindrome
{
static int count=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String array[]=s1.split("");
System.out.println("Palindromes are :");
for(int i=0;i<=array.length;i++)
{
for(int j=0;j<i;j++)
{
String B=s1.substring(j,i);
verify(B);
}
}
System.out.println("\n"+count);
sc.close();
}
public static void verify(String s1)
{
StringBuilder sb=new StringBuilder(s1);
String s2=sb.reverse().toString();
if(s1.equals(s2))
{
System.out.print(s1+" ");
count++;
}
}
}
My own logic for palindrome program for all substrings
public class Test1 {
public static void main(String[] args) {
String s = "bob";
ArrayList<Character> chr = new ArrayList<Character>();
ArrayList<String> subs= new ArrayList<String>();
for (int i=0;i<s.length();i++)
{
chr.add(s.charAt(i));
}
System.out.println(chr.toString());
StringBuilder subString = new StringBuilder();
for(int i=0; i < s.length();i++)
{
for(int j=i+1;j<s.length();j++)
{
for(int k=i;k<=j;k++)
{
subString.append(chr.get(k));
}
System.out.println(subString.toString());
subs.add(subString.toString());
subString.setLength(0);
}
}
System.out.println(subs);
for(String st : subs)
{
String st2 = new StringBuffer(st).reverse().toString();
if(st.equals(st2))
{
System.out.println(st+" is a palindrome");
}
else
{
System.out.println(st+" not a palindrome");
}
}
}
}
Print All Palindromes in the string
import java.util.*;
class AllPalindroms
{
public static void main(String args[])
{
String input = "abbaalla";
if (input.length() <= 1)
{
System.out.println("Not Palindrome Found.");
}
else
{
int length = input.length();
Set<String> set = new HashSet<String>();
for (int i = 0; i <length; i++)
{
//if(i==0)
for (int j=i+1;j<length+1;j++)
{
String s = input.substring(i, j);
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if(s.equals(sb.toString()) && s.length()>1)
{
set.add(s);
}
}
}
System.out.println(set);
}
}
}
My code to count all palindromes in a string:
import java.util.Scanner;
public class CountPalindromeSapient {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the given string: ");
String inputStr = sc.nextLine();
countPalindrome(inputStr);
System.out.println("\nTotal count of Palindromes are: "+count);
sc.close();
}
private static int countPalindrome(String inputStr) {
int count = 0;
int len = inputStr.length();
int startIndex =0;
String subString = "";
System.out.println( "Possible substrings are: ");
for (int i = 0; i < len; i++) {
for (int j = startIndex; j <= len; j++) {
subString = inputStr.substring(startIndex, j);
System.out.println(subString);
count = checkPalindrome(subString);
}
startIndex++;
}
return count;
}
private static int checkPalindrome(String subString) {
// TODO Auto-generated method stub
int subLen = subString.length();
boolean isPalindrome = false;
for(int k=0; k<subLen; k++,subLen-- ) { // Important
if (subString.charAt(k) != subString.charAt(subLen -1)) {
isPalindrome = false;
break;
}else {
isPalindrome = true;
}
}
if(isPalindrome == true) {
count ++;
}
return count;
}
}
class StringTest {
public static void main(String[] args) {
StringTest test = new StringTest();
boolean bool = test.checkPalindrom("abbaalla");
if(!bool)
System.out.println("String is not palindrom");
}
private boolean checkPalindrom(String k){
int[] count= new int[k.length()];
boolean[] arr = new boolean[k.length()];
for(int t=0;t<k.length();t++){
int j=0;
char ch = k.charAt(t);
for(int x=t+1;x<k.length();x++){
if(j<count.length){
if(ch == k.charAt(x))
count[j] = x + 1;
else
count[j] = 0;
j++;
}
}
arr[t] = workOnArr(count,t,k);
}
for(int z=0;z<arr.length;z++){
if(arr[z])
return true;
}
return false;
}
private boolean workOnArr(int[] s,int z,String w){
int j = s.length - 1;
while(j -- > 0){
if(s[j] != 0){
if(isPalindrom(w.substring(z, s[j]))){
if(w.substring(z, s[j]).length() > 1){
System.out.println(w.substring(z, s[j]).length());
System.out.println(w.substring(z, s[j]));
}
return true;
}
}
}
return false;
}
private boolean isPalindrom(String s){
int j= s.length() -1;
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(j))
return false;
j--;
}
return true;
}
}
output:-
given palindrom are:-
abba, bb, aa, alla, ll
Question: All the palindromes from a word.
public class Test4 {
public static void main(String[] args) {
String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
allpalindromicsubstrings(a);
}// main
private static void allpalindromicsubstrings(String a) {
Set<String> set = new HashSet<String>();
for (int i = 0; i < a.length(); i++) {
// odd length palindrome
expand(a, i, i, set);
// even length palindrome
expand(a, i, i + 1, set);
} // for
set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
}// ee
private static void expand(String a, int start, int last, Set<String> set) {
// run till a[start...last] is a palindrome
while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {
set.add(a.substring(start, last + 1));
// expand in both directions
start--;
last++;
}
}// ee
}
The output palindromes in the word =>
niin
ADA
eye
MADAM
iniini
GiniiniG
ii
MeyeM
ini
Print all the palindromes in a string:
public class test1 {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
System.out.println(list);
List<String> plist = new ArrayList<>();
for(int i = 0 ; i <list.size();i++) {
String curr =list.get(i);
if(ispalin(curr)) {plist.add(curr);}
}//for
System.out.println("palindrome list => " +plist);
}//main
private static boolean ispalin(String curr) {
if(curr == null || curr.length() == 0) {return false;}
return new StringBuffer(curr).reverse().toString().equals(curr);
}
}
The output is: palindrome list => [MADAM, GiniiniG]
Another Method in Java 8:
public class B {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
// list to stream
// for Multi Threaded environment
Stream<String> stream = list.parallelStream();
// also,Stream<String> stream = list.stream(); for single Threaded environment
long palindrome = stream.filter(B::isPalindrome)// find all palindromes
.peek(System.out::println) // write each match
.count();// terminal - return a count
System.out.println("Count of palindromes: " + palindrome);
// System.out.println("List => " + list);
}
private static boolean isPalindrome(String aa) {
return new StringBuffer(aa).reverse().toString().equals(aa);
}
}
Output:
GiniiniG
MADAM
Count of palindromes: 2
Java program to enter a string and frame a word by joining all the first character of each word.
Display a new word.
import java.util.*;
public class Anshu {
public static void main(String args[]) {
Scanner in = new Scanner(System.in)
System.out.println("Enter a string");
String s = in .nextLine();
char ch = s.charAt(0);
System.out.print(ch);
s = s.toUpperCase;
int l = s.length();
for (int i = 0; i < l; i++)
char a = s.charAt(i);
if (Character.isWhiteSpace())
System.out.print(s.charAt(i + 1) + "");
}
}

Splitting a sentence into words using for loop or while loop in java

i have to do a program which takes a sentence and reverses it word by word in java. for eg:
India is my country
output:aidnI si ym yrtnuoc
ive figured out all of it but i just cant split a sentence into separate words.im not allowed to use split function but im meant to use either substring or indexof();while loop and for loop are allowed.
this is what ive got so far:
import java.io.*;
public class Rereprogram10
{
public void d()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("input a string");
str=br.readLine();
String rev="";
int length=str.length();
int counter=length;
for(int i=0;i<length;i++)
{
rev=rev+str.charAt(counter-1);
counter--;
}
System.out.println("the result is: "+rev);
}
}
its wrong though,the output keeps on coming:
yrtnuoc ym si aidnI
i havent learnt arrays yet...
I'm going to assume that advanced datastructures are out, and efficiency is not an issue.
Where you are going wrong is that you are reversing the entire string, you need to only reverse the words. So you really need to check to find where a word ends, then either reverse it then, or be reversing it as you go along.
Here is an example of reversing as you go along.
int length=str.length();
String sentence="";
String word = "";
for(int i=0;i<length;i++) {
if (str.charAt(i) != ' '){
word = str.charAt(i) + word;
} else {
sentence += word +" ";
word = "";
}
}
sentence += word;
System.out.println("the result is: "+sentence);
This passes the test:
package com.sandbox;
import com.google.common.base.Joiner;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
#Test
public void testQuestionInput() {
String input = "India is my country";
assertEquals("country my is India", reverseWords(input));
}
private String reverseWords(String input) {
List<String> words = putWordsInList(input);
Collections.reverse(words);
return Joiner.on(" ").join(words);
}
private List<String> putWordsInList(String input) {
List<String> words = new ArrayList<String>();
String word = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == ' ') {
words.add(word);
word = "";
} else {
word += c;
}
}
words.add(word);
return words;
}
}
Here is my code without split() for you.
Input:
India is my country
Output:
country my is India
aidnI si ym yrtnuoc
You can choose the output you need.
public class Reverse {
public static class Stack {
private Node[] slot = new Node[1000];
private int pos = 0;
private class Node{
private char[] n = new char[30];
private int pos = 0;
public void push(char c) {
n[pos++] = c;
}
public String toString() {
return new String(n).trim() + " "; // TODO Fix
}
}
public void push(char c) {
if(slot[pos] == null)
slot[pos] = new Node();
if(c != ' ') {
slot[pos].push(c);
} else {
slot[pos++].push(c);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = pos; i >=0; i --)
sb.append(slot[i]);
return sb.toString();
}
private String reverseWord(String word) {
StringBuilder sb = new StringBuilder();
int len = word.length();
for(int i = len - 1; i >= 0; i--)
sb.append(word.charAt(i));
return sb.toString();
}
public String foryou() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < pos + 1; i ++)
sb.append(this.reverseWord(slot[i].toString()));
return sb.toString();
}
}
/**
* #param args
*/
public static void main(String[] args) {
Stack stack = new Stack();
String sentence = "India is my country";
System.out.println(sentence);
for(int i = 0; i < sentence.length(); i ++) {
stack.push(sentence.charAt(i));
}
System.out.println(stack);
System.out.println(stack.foryou());
}
}
try this
String x="India is my country";
StringBuilder b=new StringBuilder();
int i=0;
do{
i=x.indexOf(" ", 0);
String z;
if(i>0){
z=x.substring(0,i);
}
else{
z=x;
}
x=x.substring(i+1);
StringBuilder v=new StringBuilder(z);
b.append(v.reverse());
if(i!=-1)
b.append(" ");
System.out.println(b.toString());
}
while(i!=-1);

Categories

Resources