I'm a beginner at java, i have been playing around with arrays, but I can't understand whats going wrong.
This is the class:
public class StringArrayUtil {
public static void print(String [] sArray){
for(int i = 0; i<sArray.length; i++){
if(sArray[i] !=null){
System.out.println("Indice: "+i+ " String: "+sArray[i] + "\t");
}
}
}
public static int indexOf(String [] sArray, String sSearch, int s){
for(int i = s; i < sArray.length; i++){
if(sArray[i] != null && sSearch != null && sSearch.equals(sArray[i])){
return i;
}
}
return -1;
}
public static int indexOf(String [] sArray, String sSearch){
return indexOf(sArray, sSearch, 0);
}
public static int indexOfEmpty(String[] sArray){
return indexOf (sArray,null,0);
}
public static int put(String[] sArray, String newS){
for(int i = 0; i<sArray.length; i++){
if(sArray[i] == null){
sArray[i]=newS;
return i;
}
}
return -1;
}
public static int remove(String sArray, String removeS){
int times = 0;
for(int i = 0; i < sArray.length; i++){
if(removeS.equals(sArray[i]) ){
sArray[i] = null;
times ++;
}
return times;
}
}
public static String fillArray (String messege, int n){
String[] result = new String[n];
for(int i = 0; i<result.length; i++){
result[i] = Scanner.getString (messege);
}
return result;
}
}
And this is my main:
class StringArrayUtilTester {
public static void main(String [] args){
System.out.println("----------Welcome to StringMaster 2.0----------");
int z=5;
String a= "-Create a String: ";
String [] array = StringArrayUtil.fillArray(a,z);
String search = Scanner.getString("-String SearchBox! find and delete String: ");
int i = StringArrayUtil.indexOf(array, search);
if (i != -1){
System.out.println("-The String belongs to the Array!");
array[i] = null;
System.out.println("...loading....");
System.out.println("-The string has been deleted.");
}
else{
System.out.println("-String not found, try another one!");
}
String replace = Scanner.getString("-Replace with new string: ");
int e = StringArrayUtil.indexOfEmpty(array);
if(e != -1){
array[e] = replace;
}
System.out.println("-Final Array of Strings: ");
StringArrayUtil.print(array);
}
}
The errors I get when I try to javac i cant understand. Am I not doing my fillArray correctly? :
StringArrayUtilTester.java:7: error: incompatible types: String cannot be converted to String[]
array = StringArrayUtil.fillArray(a,z);
The return type on your fillArray method is String which isn't String[]
You need to make the method return a String[] by changing the return type: public String[] fillArray(...)
fillArray returns a String.
You should change the prototype to public static String[] fillArray (String messege, int n){
The return type of fillArray should be String[]
public static String[] fillArray (String messege, int n){
String[] result = new String[n];
for(int i = 0; i<result.length; i++){
result[i] = Scanner.getString (messege);
}
return result;
}
Two problems in the method fillArray
The method is expecting a String but you return a String[]. Probably the method signature should be String[]
Scanner doesn't have a static method getString
You need to create an instance of Scanner prior to using it:
Scanner scan = new Scanner(System.in);
Then you can do
result[i] = scan.next();
Related
This is my code to count the number of rotations.
But IDK, What is the problem with it.
Can anyone explain and help me out.
Test Case: Input: david vidda
Output: 2
I tried to have brute force approach but, that wasn't working even.
Can anyone point out my mistake??
import java.util.*;
class solution{
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2)
{
int i;
int count =0;
for (i = 0; i < str1.length(); i++){
if(str1.equals(str2))
{
count++;
str1 = leftRotatebyOne(str1);
System.out.println(str1);
}
else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str)
{
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1));
str.setCharAt(i,temp);
return str;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String strr1= in.nextLine();
StringBuilder str1 = new StringBuilder(strr1);
String strr2 = in.nextLine();
StringBuilder str2 = new StringBuilder(strr2);
System.out.print(arrayLeftRotation(str1, str2));
}
}
Your method leftRotateByOne appears more complicated than necessary.
Try this:
public class Solution
{
public static int arrayLeftRotation(String str1,
String str2)
{
int nr_rotate;
int counter;
nr_rotate = 0;
for (counter = 0; counter < str1.length(); counter++)
{
if (str1.equals(str2))
return (nr_rotate);
else
{
str1 = leftRotateByOne(str1);
nr_rotate++;
System.out.println(str1);
}
}
// No possible solution
return (-1);
} // arrayLeftRotation
public static String leftRotateByOne(String str)
{
return (str.substring(1) + str.charAt(0));
}
public static void main(String[] args)
{
String str1 = "david";
String str2 = "vidda";
System.out.print(arrayLeftRotation(str1, str2));
}
} // class Solution
Another possible solution for arrayLeftRotation,
public static int arrayLeftRotation(String str1, String str2) {
StringBuilder builder = new StringBuilder(str1);
for (int i = 0; i < str1.length(); i++) {
builder.append(str1.charAt(i)).delete(0, 1);
if (str2.equals(builder.toString())) {
return i + 1;
}
}
return -1;
}
Note: this will return -1 if no matches found.
The trick is to append the input string to itself, then call String#indexOf. It will give you the index at which the doubled string contains the expected string, which is what you're looking for.
Example:
public static int numberOfRotations(String input, String expected) {
final String doubledInput = input + input;
return doubledInput.indexOf(expected);
}
If you really want to implement it yourself, you need to simplify your code to minimize the possibility of making mistakes.
public static String rotate(String input) {
return input.substring(1) + input.charAt(0);
}
public static int numberOfRotations(String input, String expected) {
// handle edge cases (null, empty, etc.) here
String rotatedInput = input;
int count = 0;
while (!rotatedInput.equals(expected) && count < input.length()) {
rotatedInput = rotate(rotatedInput);
count++;
}
return count == input.length() ? -1 : count;
}
I am just trying to point out where your error lies and fix it.
Your error lies here in your leftRotatebyOne:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1)); // your error while shifting to the left;
What you are trying to do is shifting one position to the left, and you should just do it as:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(i,str.charAt(i+1));
And then your method will work.
But I have to say Alex M has provided a cleaner solution to your problem. Perhaps you should have a try.
Your solution then can be (after the fix):
public class RotationCount {
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2) {
int i;
int count = 0;
for (i = 0; i < str1.length(); i++) {
if (!str1.toString().equals(str2.toString())) {
count++;
str1 = leftRotatebyOne(str1);
} else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str) {
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length() - 1; i++) {
str.setCharAt(i, str.charAt(i + 1));
}
str.setCharAt(i, temp);
return str;
}
public static void main(String[] args) {
StringBuilder str1 = new StringBuilder("david");
StringBuilder str2 = new StringBuilder("vidda");
System.out.print(arrayLeftRotation(str1, str2));
}
}
I want to search how many times a string appear in another string
It does not work correctly when i put an similar string at the end.
public class C3_Project3_WPr {
public static void main(String[] args) {
String strn1="AliAliAli";
String strn2="AliAliSinaAli";
String strn3="Ali";
int count1=StringCounter(strn1, strn3);
System.out.println(count1);
int count2=StringCounter(strn2, strn3);
System.out.println(count2);
}
//ُString in String Method
static int StringCounter(String str1, String str2){
int counter=0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for(int i= 0; i<str1.length(); i++){
if(str1.contains(str2)){
counter++;
str1= str1.substring(str2.length());
}
}
return counter;
}
}
Solution to your problem is here
public static void main(String[] args) {
String strn1 = "AliAliAliwewdwdweAli";
String strn2 = "AliAliSinaAliAlAli";
String strn3 = "Ali";
int count1 = StringCounter(strn1, strn3);
System.out.println(count1);
int count2 = StringCounter(strn2, strn3);
System.out.println(count2);
}
// ُString in String Method
static int StringCounter(String str1, String str2) {
int counter = 0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for (int i = str1.indexOf(str2); i >= 0; i = str1.indexOf(str2, i + str2.length())) {
counter++;
}
return counter;
}
}
When modifying str1 you only take in to account the length of the search string, but ignore the index in which it was found. Fixing this (e.g., by using indexOf), will fix your results too:
int index = str1.indexOf(str2);
while (index >= 0) {
counter++;
index = str1.indexOf(str2, index + str2.length());
}
Use recursive method: It's quick and easy way to solve your problem:
static int StringCounter(String str1, String str2){
return (str1.contains(str2)) ? 1 + StringCounter(str1.replaceFirst(str2, ""), str2) : 0;
}
String[] enc=new String[]{"w","e","l","c","o","m"};
String[] cod=new String[] {"111","10","00","110","010","011"};
String real="";
int sindex=0;
int eindex=1;
String cdd="111100011001001110";
StringBuilder code=new StringBuilder(cdd);
String temp;
for(int i=0;i<code.length();i++){
temp=code.substring(sindex, eindex++);
if(Arrays.asList(cod).contains(temp)){
int j=Arrays.asList(cod).indexOf(temp);
int z=code.indexOf(temp);
StringBuilder y = code.delete(z, z+temp.length());
temp=y.toString();
real+=enc[j];
System.out.println(y);
}
}
I have these two arrays enc[] and cod[], contains characters and codes respectively what i want to do is just check each value of cod array in cdd string and replace it with its respective String from enc[]...
By running this code i am getting only "w" while the result was suppose to be "welcome".
Try this code - i have refactored yours :)
public class enc {
private static boolean valueFound=false;
public static void main(String[] args) {
String[] enc=new String[]{"w","e","l","c","o","m"};
String[] cod=new String[] {"111","10","00","110","010","011"};
String real="";
int sindex=0;
int eindex=1;
String cdd="111100011001001110";
do {
for (int i = 0; i < cod.length; i++) {
if (cdd.startsWith(cod[i])) {
real += enc[i];
cdd = cdd.substring(cod[i].length());
valueFound = true;
} else {
valueFound = false;
}
}
}
while(valueFound);
System.out.println(real);
}
}
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);
}
}
Hi I've been doing this java program, i should input a string and output the longest palindrome that can be found ..
but my program only output the first letter of the longest palindrome .. i badly need your help .. thanks!
SHOULD BE:
INPUT : abcdcbbcdeedcba
OUTPUT : bcdeedcb
There are two palindrome strings : bcdcb and bcdeedcb
BUT WHEN I INPUT : abcdcbbcdeedcba
output : b
import javax.swing.JOptionPane;
public class Palindrome5
{ public static void main(String args[])
{ String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
for(int x=0; x<size; x++)
{ for(int y=x+1; y<size-x; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
Out = GetLongest(subword);
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
public static String GetLongest(String sWord)
{
int sLength = sWord.length();
String Lpalindrome = "";
int storage = 0;
if(storage<sLength)
{
storage = sLength;
Lpalindrome = sWord;
}
return(Lpalindrome);
}
}
modified program..this program will give the correct output
package pract1;
import javax.swing.JOptionPane;
public class Palindrome5
{
public static void main(String args[])
{
String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
String Lpalindrome = "";
int storage=0;
String out="";
for(int x=0; x<size; x++)
{ for(int y=x+1; y<=size; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
int sLength = subword.length();
if(storage<sLength)
{
storage = sLength;
Lpalindrome = subword;
out=Lpalindrome;
}
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
}
You have two bugs:
1.
for(int y=x+1; y<size-x; y++)
should be
for(int y=x+1; y<size; y++)
since you still want to go all the way to the end of the string. With the previous loop, since x increases throughout the loop, your substring sizes decrease throughout the loop (by removing x characters from their end).
2.
You aren't storing the longest string you've found so far or its length. The code
int storage = 0;
if(storage<sLength) {
storage = sLength;
...
is saying 'if the new string is longer than zero characters, then I will assume it is the longest string found so far and return it as LPalindrome'. That's no help, since we may have previously found a longer palindrome.
If it were me, I would make a static variable (e.g. longestSoFar) to hold the longest palindrome found so far (initially empty). With each new palindrome, check if the new one is longer than longestSoFar. If it is longer, assign it to longestSoFar. Then at the end, display longestSoFar.
In general, if you're having trouble 'remembering' something in the program (e.g. previously seen values) you have to consider storing something statically, since local variables are forgotten once their methods finish.
public class LongestPalindrome {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}
public static void printLongestPalindrome(String S)
{
int maxBack=-1;
int maxFront = -1;
int maxLength=0;
for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
{
int back = potentialCenter-1;
int front = potentialCenter + 1;
int longestPalindrome = 0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome+1;
maxBack = back + 1;
maxFront = front;
}
back = potentialCenter;
front = potentialCenter + 1;
longestPalindrome=0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome;
maxBack = back + 1;
maxFront = front;
}
}
if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
else{
System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
}
}
}
I have my own way to get longest palindrome in a random word. check this out
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.
public class LongestPalindrome {
public static void main(String[] args) {
HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
}
private static HashMap<String, Integer> findLongestPalindrome(String str) {
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (i < str.length()) {
String alpha = String.valueOf(str.charAt(i));
if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
if (isPalindrome(pali)) {
map.put(pali, pali.length());
i = str.lastIndexOf(str.charAt(i));
}
}
i++;
}
return map;
}
public static boolean isPalindrome(String input) {
for (int i = 0; i <= input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}
}
This approach is simple.
Output:
String:abcdeedcba Value:10
String:4444 Value:4
String:6776 Value:4
String:ghihg Value:5
This is my own way to get longest palindrome. this will return the length and the palindrome word
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.