How to find a particular name repeated how many number of times? - java

I'm recieving issue with the output can anyone help me with it?
It is a code for finding how many times a particular name has been repeated.
package example1;
import java.util.Scanner;
public class example1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j,t,c;
String a[]=new String[10];
String b[]=new String[10];
Scanner sc=new Scanner(System.in);
for(i=0;i<10;i++)
{
a[i]=sc.nextLine();
b[i]=a[i];
}
for(i=0;i<10;i++)
{
c=0;
for(j=i+1;j<9;j++)
{
if(b[j]==b[i])
{
c++;
for(t=j;t<10;t++)
{
b[t]=b[t+1];
}
}
}
System.out.print(b[i]+" is repeated "+ c +" times ");
}
}
}

Try this.
String[] arr = new String[] {"a","b","c","d","a","b","c","a","b","a"};
List<String> list = Arrays.asList(arr);
Set<String> set = new HashSet<>(list);
for(String name : set)
System.out.println(name + " is repeated " + Collections.frequency(list, name) + " times");
If you want your comparison to be case insensitive, then try this.
String[] arr = new String[] {"A","B","c","D","a","b","c","a","b","a"};
List<String> list = new ArrayList<>(10);
for(String name : arr)
list.add(name.toLowerCase());
Set<String> set = new HashSet<>(list);
for(String name : set)
System.out.println(name + " is repeated " + Collections.frequency(list, name) + " times");
Will require more space though.

The following code should help for determining the repetition
public class Repetation {
public static void main(String[] args) {
String string = "Sam sam is good boy james is sams friend clyra is clyra";
int count;
string = string.toLowerCase();
String words[] = string.split(" ");
System.out.println("Duplicate words: ");
for(int i = 0; i < words.length; i++) {
count = 1;
for(int j = i+1; j < words.length; j++) {
if(words[i].equals(words[j])) {
count++;
words[j] = "0";//making it 0 for future reference
}
}
if(count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}

public static int countWord(String input, String text) {
int index = input.indexOf(text);
if (index == -1 || text.isEmpty()) {
return 0;
}
int count = 0;
do {
count++;
index = input.indexOf(text, index + text.length());
} while (index > 0 && index < input.length());
return count;
}
This code will return 4:
int total = countWord("abcs8abc88habcabci7h", "abc");

Related

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 to count String repition in String Array

I am trying to count the amount of times a word is repeated in stdin.
Example input:
This is a test, this is is
Desired output:
this 2
is 3
a 1
test 1
I have an int[] to store the wordCount but I'm not sure where to use it, the int count is just temporary so the program can run.
Here is my code for reference:
import java.util.Scanner;
public class WCount {
public static void main (String[] args) {
Scanner stdin = new Scanner(System.in);
String [] wordArray = new String [10000];
int [] wordCount = new int [10000];
int numWords = 0;
while(stdin.hasNextLine()){
String s = stdin.nextLine();
String [] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\\
s+"); //stores strings as words after converting to lowercase and getting rid of punctuation
for(int i = 0; i < words.length; i++){
int count = 0; //temporary so program can run
for(int j = 0; j < words.length; j++){
if( words[i] == words[j] )
count++;
System.out.println("word count: → " + words[i] + " " + count);
}
}
}
I would use something like this:
import java.util.ArrayList;
import java.util.Scanner;
public class WCount {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String[] wordArray = new String[10000];
int[] wordCount = new int[10000];
int numWords = 0;
while (stdin.hasNextLine()) {
String s = stdin.nextLine();
ArrayList<String> noDuplicated = new ArrayList<String>();
String[] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase()
.split("\\s+"); // stores strings as words after converting
// to lowercase and getting rid of
// punctuation
//Array that contains the words without the duplicates ones
for (int i = 0; i < words.length; i++) {
if(!noDuplicated.contains(words[i]))
noDuplicated.add(words[i]);
}
//Count and print the words
for(int i=0; i<noDuplicated.size();i++){
int count = 0;
for (int j = 0; j < words.length; j++) {
if (noDuplicated.get(i).equals(words[j]))
count++;
}
System.out.println("word count: → " + words[i] + " "
+ count);
}
}
}
}
output:
This is a test, this is is
word count: → this 2
word count: → is 3
word count: → a 1
word count: → test 1
Hope it is usefull!
This works for me. Although iterating through the complete possible array is silly. It would work easier with ArrayList. But as I am not sure if you are allowed to use it.
import java.util.Scanner;
public class WCount {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int[] wordCount = new int[1000];
String[] wordList = new String[1000];
int j = 0;
while (stdin.hasNextLine()) {
String s = stdin.nextLine();
String[] words = s.split("\\W+");
for (String word : words) {
int listIndex = -1;
for (int i = 0; i < wordList.length; i++) {
if (word.equals(wordList[i])) {
listIndex = i;
}
}
if (listIndex > -1) {
wordCount[listIndex]++;
} else {
wordList[j] = word;
wordCount[j]++;
j++;
}
}
for (int i = 0; i < j; i++) {
System.out.println("the word: " + wordList[i] + " occured " + wordCount[i] + " time(s).");
}
}
}
}
output:
this is a test. this is cool.
the word: this occured 2 time(s).
the word: is occured 2 time(s).
the word: a occured 1 time(s).
the word: test occured 1 time(s).
the word: cool occured 1 time(s).
You can use a hash table here. I am not going to write code for you, but here is simple pseudo algorithm:
if hashTable contains word
hashTable.put(word, words.value + 1)
else hashTable.put(word, 1)
Do this for each word in the word array. After all the words have been handled, you simply print each key (word) in the hash table with its value (number of times it appeared).
Hope this helps!
figured this out...simpler way..
import java.util.Vector;
public class Get{
public static void main(String[]args){
Vector<String> ch = new Vector<String>();
String len[] = {"this", "is", "this", "test", "is", "a", "is"};
int count;
for(int i=0; i<len.length; i++){
count=0;
for(int j=0; j<len.length; j++){
if(len[i]==len[j]){
count++;
}
}
if(count>0){
if(!ch.contains(len[i])){
System.out.println(len[i] + " - " + count);
ch.add(len[i]);
}
}
}
}
}
Output:
this - 2
is - 3
test - 1
a - 1
My implementation:
public static void main(final String[] args) {
try (Scanner stdin = new Scanner(System.in)) {
while (stdin.hasNextLine()) {
Map<String, AtomicInteger> termCounts = new HashMap<>();
String s = stdin.nextLine();
String[] words = s.toLowerCase().split("[^a-zA-Z]+");
for (String word : words) {
AtomicInteger termCount = termCounts.get(word);
if (termCount == null) {
termCount = new AtomicInteger();
termCounts.put(word, termCount);
}
termCount.incrementAndGet();
}
for (Entry<String, AtomicInteger> termCount : termCounts.entrySet()) {
System.out.println("word count: " + termCount.getKey() + " " + termCount.getValue());
}
}
}
}

Counting words from array in a string

I have an array of string say
A=["hello", "you"]
I have a string, say
s="hello, hello you are so wonderful"
I need to count the number of occurrence of strings from A in s.
In this case, the number of occurrences is 3 (2 "hello", 1 "you").
How to do this effectively? (A might contains lots of words, and s might be long in practice)
Try:
Map<String, Integer> wordCount = new HashMap<>();
for(String a : dictionnary) {
wordCount.put(a, 0);
}
for(String s : text.split("\\s+")) {
Integer count = wordCount.get(s);
if(count != null) {
wordCount.put(s, count + 1);
}
}
public void countMatches() {
String[] A = {"hello", "you"};
String s = "hello, hello you are so wonderful";
String patternString = "(" + StringUtils.join(A, "|") + ")";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
Note that StringUtils is from apache commons. If you don't want to include and additional jar you can just construct that string using a for loop.
HashSet<String> searchWords = new HashSet<String>();
for(String a : dictionary) {
searchWords.add(a);
}
int count = 0;
for(String s : input.split("[ ,]")) {
if(searchWords.contains(s)) {
count++;
}
}
int count =0;
for(int i=0;i<A.length;i++)
{
count = count + s.split(A[i],-1).length - 1;
}
Working Ideone : http://ideone.com/Z9K3JX
This is fully working method with output :)
public static void main(String[] args) {
String[] A={"hello", "you"};
String s= "hello, hello you are so wonderful";
int[] count = new int[A.length];
for (int i = 0; i < A.length; i++) {
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
}
for (int i = 0; i < count.length; i++) {
System.out.println(A[i] + ": " + count[i]);
}
}
What does this line do?
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
This part s.replaceAll(A[i], "") changes all "hello" to empty "" string in the text.
So I take the length of everything s.length() I substract from it the length of same string without that word s.replaceAll(A[i], "").length() and I divide it by the length of that word /A[i].length()
Sample output for this example :
hello: 2
you: 1
You can use the String Tokenizer
Do something like this:
A = ["hello", "you"];
s = "hello, hello you are so wonderful";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreElements()) {
for (String i: A) {
if(st.nextToken() == i){
//You can keep going from here
}
}
}
This is what I came up with:
It doesn't create any new objects. It uses String.indexOf(String, int), keeps track of the current index, and increments the occurance-count.
public class SearchWordCount {
public static final void main(String[] ignored) {
String[] searchWords = {"hello", "you"};
String input = "hello, hello you are so wonderful";
for(int i = 0; i < searchWords.length; i++) {
String searchWord = searchWords[i];
System.out.print(searchWord + ": ");
int foundCount = 0;
int currIdx = 0;
while(currIdx != -1) {
currIdx = input.indexOf(searchWord, currIdx);
if(currIdx != -1) {
foundCount++;
currIdx += searchWord.length();
} else {
currIdx = -1;
}
}
System.out.println(foundCount);
}
}
}
Output:
hello: 2
you: 1

Find duplicate characters in a String and count the number of occurrences using Java

How can I find the number of occurrences of a character in a string?
For example: The quick brown fox jumped over the lazy dog.
Some example outputs are below,
'a' = 1
'o' = 4
'space' = 8
'.' = 1
You could use the following, provided String s is the string you want to process.
Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
int cnt = map.get(c);
map.put(c, ++cnt);
} else {
map.put(c, 1);
}
}
Note, it will count all of the chars, not only letters.
Java 8 way:
"The quick brown fox jumped over the lazy dog."
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
void Findrepeter(){
String s="mmababctamantlslmag";
int distinct = 0 ;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if(s.charAt(i)==s.charAt(j))
{
distinct++;
}
}
System.out.println(s.charAt(i)+"--"+distinct);
String d=String.valueOf(s.charAt(i)).trim();
s=s.replaceAll(d,"");
distinct = 0;
}
}
import java.io.*;
public class CountChar
{
public static void main(String[] args) throws IOException
{
String ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Statement:");
ch=br.readLine();
int count=0,len=0;
do
{
try
{
char name[]=ch.toCharArray();
len=name.length;
count=0;
for(int j=0;j<len;j++)
{
if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123)))
count++;
}
if(count!=0)
System.out.println(name[0]+" "+count+" Times");
ch=ch.replace(""+name[0],"");
}
catch(Exception ex){}
}
while(len!=1);
}
}
Output
Enter the Statement:asdf23123sfsdf
a 1 Times
s 3 Times
d 2 Times
f 3 Times
A better way would be to create a Map to store your count. That would be a Map<Character, Integer>
You need iterate over each character of your string, and check whether its an alphabet. You can use Character#isAlphabetic method for that. If it is an alphabet, increase its count in the Map. If the character is not already in the Map then add it with a count of 1.
NOTE: - Character.isAlphabetic method is new in Java 7. If you are using an older version, you should use Character#isLetter
String str = "asdfasdfafk asd234asda";
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
char[] arr = str.toCharArray();
for (char value: arr) {
if (Character.isAlphabetic(value)) {
if (charMap.containsKey(value)) {
charMap.put(value, charMap.get(value) + 1);
} else {
charMap.put(value, 1);
}
}
}
System.out.println(charMap);
OUTPUT: -
{f=3, d=4, s=4, a=6, k=1}
If your string only contains alphabets then you can use some thing like this.
public class StringExample {
public static void main(String[] args) {
String str = "abcdabghplhhnfl".toLowerCase();
// create a integer array for 26 alphabets.
// where index 0,1,2.. will be the container for frequency of a,b,c...
Integer[] ar = new Integer[26];
// fill the integer array with character frequency.
for(int i=0;i<str.length();i++) {
int j = str.charAt(i) -'a';
if(ar[j]==null) {
ar[j]= 1;
}else {
ar[j]+= 1;
}
}
// print only those alphabets having frequency greater then 1.
for(int i=0;i<ar.length;i++) {
if(ar[i]!=null && ar[i]>1) {
char c = (char) (97+i);
System.out.println("'"+c+"' comes "+ar[i]+" times.");
}
}
}
}
Output:
'a' comes 2 times.
'b' comes 2 times.
'h' comes 3 times.
'l' comes 2 times.
Finding the duplicates in a String:
Example 1 : Using HashMap
public class a36 {
public static void main(String[] args) {
String a = "Gini Rani";
fix(a);
}//main
public static void fix(String a ){
Map<Character ,Integer> map = new HashMap<>();
for (int i = 0; i <a.length() ; i++ ) {
char ch = a.charAt(i);
map.put(ch , map.getOrDefault(ch,0) +1 );
}//for
List<Character> list = new ArrayList<>();
Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();
for ( Map.Entry<Character ,Integer> entry : entrySet) {
list.add( entry.getKey() );
System.out.printf( " %s : %d %n" , entry.getKey(), entry.getValue() );
}//for
System.out.println("Duplicate elements => " + list);
}//fix
}
Example 2 : using Arrays.stream() in Java 8
public class a37 {
public static void main(String[] args) {
String aa = "Protijayi Gini";
String[] stringarray = aa.split("");
Map<String , Long> map = Arrays.stream(stringarray)
.collect(Collectors.groupingBy(c -> c , Collectors.counting()));
map.forEach( (k, v) -> System.out.println(k + " : "+ v) );
}
}
This is the implementation without using any Collection and with complexity order of n. Although the accepted solution is good enough and does not use Collection as well but it seems, it is not taking care of special characters.
import java.util.Arrays;
public class DuplicateCharactersInString {
public static void main(String[] args) {
String string = "check duplicate charcters in string";
string = string.toLowerCase();
char[] charAr = string.toCharArray();
Arrays.sort(charAr);
for (int i = 1; i < charAr.length;) {
int count = recursiveMethod(charAr, i, 1);
if (count > 1) {
System.out.println("'" + charAr[i] + "' comes " + count + " times");
i = i + count;
} else
i++;
}
}
public static int recursiveMethod(char[] charAr, int i, int count) {
if (ifEquals(charAr[i - 1], charAr[i])) {
count = count + recursiveMethod(charAr, ++i, count);
}
return count;
}
public static boolean ifEquals(char a, char b) {
return a == b;
}
}
Output :
' ' comes 4 times
'a' comes 2 times
'c' comes 5 times
'e' comes 3 times
'h' comes 2 times
'i' comes 3 times
'n' comes 2 times
'r' comes 3 times
's' comes 2 times
't' comes 3 times
public class dublicate
{
public static void main(String...a)
{
System.out.print("Enter the String");
Scanner sc=new Scanner(System.in);
String st=sc.nextLine();
int [] ar=new int[256];
for(int i=0;i<st.length();i++)
{
ar[st.charAt(i)]=ar[st.charAt(i)]+1;
}
for(int i=0;i<256;i++)
{
char ch=(char)i;
if(ar[i]>0)
{
if(ar[i]==1)
{
System.out.print(ch);
}
else
{
System.out.print(ch+""+ar[i]);
}
}
}
}
}
Use google guava Multiset<String>.
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<E> entry:wordsMultiset.entrySet()){
System.out.println(entry.getElement()+" - "+entry.getCount());
}
public static void main(String args[]) {
char Char;
int count;
String a = "Hi my name is Rahul";
a = a.toLowerCase();
for (Char = 'a'; Char <= 'z'; Char++) {
count = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == Char) {
count++;
}
}
System.out.println("Number of occurences of " + Char + " is " + count);
}
}
public static void main(String[] args) {
String name="AnuvratAnuvra";
char[] arr = name.toCharArray();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(char val:arr){
map.put(val,map.containsKey(val)?map.get(val)+1:1);
}
for (Entry<Character, Integer> entry : map.entrySet()) {
if(entry.getValue()>1){
Character key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":"+value);
}
}
}
class A {
public static void getDuplicates(String S) {
int count = 0;
String t = "";
for (int i = 0; i < S.length() - 1; i++) {
for (int j = i + 1; j < S.length(); j++) {
if (S.charAt(i) == S.charAt(j) && !t.contains(S.charAt(j) + "")) {
t = t + S.charAt(i);
}
}
}
System.out.println(t);
}
}
class B
public class B {
public static void main(String[] args){
A.getDuplicates("mymgsgkkabcdyy");
}
}
You can also achieve it by iterating over your String and using a switch to check each individual character, adding a counter whenever it finds a match. Ah, maybe some code will make it clearer:
Main Application:
public static void main(String[] args) {
String test = "The quick brown fox jumped over the lazy dog.";
int countA = 0, countO = 0, countSpace = 0, countDot = 0;
for (int i = 0; i < test.length(); i++) {
switch (test.charAt(i)) {
case 'a':
case 'A': countA++; break;
case 'o':
case 'O': countO++; break;
case ' ': countSpace++; break;
case '.': countDot++; break;
}
}
System.out.printf("%s%d%n%s%d%n%s%d%n%s%d", "A: ", countA, "O: ", countO, "Space: ", countSpace, "Dot: ", countDot);
}
Output:
A: 1
O: 4
Space: 8
Dot: 1
import java.util.HashMap;
import java.util.Scanner;
public class HashMapDemo {
public static void main(String[] args) {
//Create HashMap object to Store Element as Key and Value
HashMap<Character,Integer> hm= new HashMap<Character,Integer>();
//Enter Your String From Console
System.out.println("Enter an String:");
//Create Scanner Class Object From Retrive the element from console to our java application
Scanner sc = new Scanner(System.in);
//Store Data in an string format
String s1=sc.nextLine();
//find the length of an string and check that hashmap object contain the character or not by using
//containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value
for(int i=0;i<s1.length();i++){
if(!hm.containsKey(s1.charAt(i))){
hm.put(s1.charAt(i),(Integer)1);
}//if
else{
hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
}//else
}//for
System.out.println("The Charecters are:"+hm);
}//main
}//HashMapDemo
There are three ways to find duplicates
public class WAP_PrintDuplicates {
public static void main(String[] args) {
String input = "iabccdeffghhijkkkl";
findDuplicate1(input);
findDuplicate2(input);
findDuplicate3(input);
}
private static void findDuplicate3(String input) {
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < input.length() - 1; i++) {
int ch = input.charAt(i);
if (hm.containsKey(input.charAt(i))) {
int value = hm.get(input.charAt(i));
hm.put(input.charAt(i), value + 1);
} else {
hm.put(input.charAt(i), 1);
}
}
Set<Entry<Character, Integer>> entryObj = hm.entrySet();
for (Entry<Character, Integer> entry : entryObj) {
if (entry.getValue() > 1) {
System.out.println("Duplicate: " + entry.getKey());
}
}
}
private static void findDuplicate2(String input) {
int i = 0;
for (int j = i + 1; j < input.length(); j++, i++) {
if (input.charAt(i) == input.charAt(j)) {
System.out.println("Duplicate is: " + input.charAt(i));
}
}
}
private static void findDuplicate1(String input) {
// TODO Auto-generated method stub
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j < input.length(); j++) {
if (input.charAt(i) == input.charAt(j)) {
System.out.println("Duplicate is: " + input.charAt(i));
}
}
}
}
}
Using Eclipse Collections CharAdapter and CharBag:
CharBag bag =
Strings.asChars("The quick brown fox jumped over the lazy dog.").toBag();
Assert.assertEquals(1, bag.occurrencesOf('a'));
Assert.assertEquals(4, bag.occurrencesOf('o'));
Assert.assertEquals(8, bag.occurrencesOf(' '));
Assert.assertEquals(1, bag.occurrencesOf('.'));
Note: I am a committer for Eclipse Collections
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCountChar{
public static void main(String[] args) {
Scanner inputString = new Scanner(System.in);
String token = inputString.nextLine();
char[] ch = token.toCharArray();
Map<Character, Integer> dupCountMap = new HashMap<Character,Integer>();
for (char c : ch) {
if(dupCountMap.containsKey(c)) {
dupCountMap.put(c, dupCountMap.get(c)+1);
}else {
dupCountMap.put(c, 1);
}
}
for (char c : ch) {
System.out.println("Key = "+c+ "Value : "+dupCountMap.get(c));
}
Set<Character> keys = dupCountMap.keySet();
for (Character character : keys) {
System.out.println("Key = "+character+ " Value : " + dupCountMap.get(character));
}
}**
In java... using for loop:
import java.util.Scanner;
/**
*
* #author MD SADDAM HUSSAIN */
public class Learn {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
char process[] = input.toCharArray();
boolean status = false;
int index = 0;
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process.length; j++) {
if (i == j) {
continue;
} else {
if (process[i] == process[j]) {
status = true;
index = i;
break;
} else {
status = false;
}
}
}
if (status) {
System.out.print("" + process[index]);
}
}
}
}
public class StringCountwithOutHashMap {
public static void main(String[] args) {
System.out.println("Plz Enter Your String: ");
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
int count = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s1.length(); j++) {
if (s1.charAt(i) == s1.charAt(j)) {
count++;
}
}
System.out.println(s1.charAt(i) + " --> " + count);
String d = String.valueOf(s1.charAt(i)).trim();
s1 = s1.replaceAll(d, "");
count = 0;
}}}
public class CountH {
public static void main(String[] args) {
String input = "Hi how are you";
char charCount = 'h';
int count = 0;
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == charCount) {
count++;
}
}
System.out.println(count);
}
}
public class DuplicateValue {
public static void main(String[] args) {
String s = "hezzz";
char []st=s.toCharArray();
int count=0;
Set<Character> ch=new HashSet<>();
for(Character cg:st){
if(ch.add(cg)==false){
int occurrences = Collections.frequency(ch, cg);
count+=occurrences;
if(count>1){
System.out.println(cg + ": This character exist more than one time");
}
else{
System.out.println(cg);
}
}
}
System.out.println(count);
}
}
Map<Character,Integer> listMap = new HashMap<Character,Integer>();
Scanner in= new Scanner(System.in);
System.out.println("enter the string");
String name=in.nextLine().toString();
Integer value=0;
for(int i=0;i<name.length();i++){
if(i==0){
listMap.put(name.charAt(0), 1);
}
else if(listMap.containsKey(name.charAt(i))){
value=listMap.get(name.charAt(i));
listMap.put(name.charAt(i), value+1);
}else listMap.put(name.charAt(i),1);
}
System.out.println(listMap);
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String reverse1;
String reverse2;
int count = 0;
while(n > 0)
{
String A = sc.next();
String B = sc.next();
reverse1 = new StringBuffer(A).reverse().toString();
reverse2 = new StringBuffer(B).reverse().toString();
if(!A.equals(reverse1))
{
for(int i = 0; i < A.length(); i++)
{
for(int j = 0; j < A.length(); j++)
{
if(A.charAt(j) == A.charAt(i))
{
count++;
}
}
if(count % 2 != 0)
{
A.replace(A.charAt(i),"");
count = 0;
}
}
System.out.println(A);
}
n--;
}
}
}
public class list {
public static String name(Character k){
String s="the quick brown fox jumped over the lazy dog.";
int count=0;
String l1="";
String l="";
List<Character> list=new ArrayList<Character>();
for(int i1=0;i1<s.length();i1++){
list.add(s.charAt(i1));
}
list.sort(null);
for (Character character : list) {
l+=character;
}
for (int i1=0;i1<l.length();i1++) {
if((l.charAt(i1)==k)){
count+=1;
l1=l.charAt(i1)+" "+Integer.toString(count);
if(k==' '){
l1="Space"+" "+Integer.toString(count);
}
}else{
count=0;
}
}
return l1;
}
public static void main(String[] args){
String g = name('.');
System.out.println(g);
}
}
Simple and Easy way to find char occurrences >
void findOccurrences() {
String s = "The quick brown fox jumped over the lazy dog.";
Map<String, Integer> occurrences = new LinkedHashMap<String, Integer>();
for (String ch : s.split("")) {
Integer count = occurrences.get(ch);
occurrences.put(ch, count == null ? 1 : count + 1);
}
System.out.println(occurrences);
}
This will print output as:
{T=1, h=2, e=4, =8, q=1, u=2, i=1, c=1, k=1, b=1, r=2, o=4, w=1, n=1, f=1, x=1, j=1, m=1, p=1, d=2, v=1, t=1, l=1, a=1, z=1, y=1, g=1, .=1}
String str = "anand";
Map<Character, Integer> map
= new HashMap<Character, Integer>();
// Converting string into a char array
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (map.containsKey(c)) {
// If character is present increment count by 1
map.put(c, map.get(c) + 1);
}
else {
// If character is not present
//putting this character into map with 1 as it's value.
map.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry :
map.entrySet()) {
System.out.println(entry.getKey()
+ " : "
+ entry.getValue());
}
Output:
a:2 n:2 d:1
Use the below code snippet
import java.util.HashMap;
import java.util.Map;
public class CountDuplicateChar {
public static void main(String... strings) {
withSortedString("aaaaabbcccccc");
withUnSortedString("aaaaab bcc *#ccccf");
withHashMap("bala");
}
private static void withHashMap(String inputString) {
Map<Character, Integer> map = new HashMap<>();
char[] charArray = inputString.toCharArray();
for (int i = 0 ; i < charArray.length ; i++ ){
if (map.containsKey(charArray[i])) {
map.put(charArray[i], map.get(charArray[i]) +1);
} else {
map.put(charArray[i], 1);
}
}
System.out.println(map);
}
private static void withUnSortedString(String unSortedString) {
int len = 0;
do {
char[] ch = unSortedString.toCharArray();
if (ch.length ==0)
break;
int count = 0 ;
for ( int i = 0 ; i < ch.length; i++) {
if (ch[0] == ch[i]) {
count++;
}
}
System.out.println(ch[0] + " - " + count + "times");
unSortedString = unSortedString.replace(""+ch[0],"");
}while (len!=1);
}
private static void withSortedString(String s) {
for(int i=0; i<s.length(); i++)
{
System.out.print(s.charAt(i)+""+(s.lastIndexOf(s.charAt(i))-s.indexOf(s.charAt(i))+1));
i = s.lastIndexOf(s.charAt(i));
}
System.out.println(" ");
}
}
Using Java 8 streams with groupingBy()
//way 1
String name = "anandha";
Map<Character,Long> map = name.chars()
.mapToObj(ch -> (char)ch)
.collect(Collectors.groupingBy(ch -> ch, Collectors.counting());
System.out.println(map);
using LinkedHashmap
//way2
String name = "anandha";
char[] charArray = name.toChararray();
Map<Character,Integer> map = new LinkedHashmap<>();
for(char ch: charArray)
{
if(map.containsKey(ch))
{
map.put(ch,map.get(ch)+1);
}else
{
map.put(ch,1)
}
}
map.foreach((key,value)->{
{
System.out.println(key +" : "+ value);
}
});
//(OR) iterate map using the way above or below
for(Map.Entry mp: map.entrySet())
{
System.out.println(mp.getKey()+" : "+ mp.getValue());
}
}
public static void main(String[] args) {
char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
char[][] countArr = new char[array.length][2];
int lastIndex = 0;
for (char c : array) {
int foundIndex = -1;
for (int i = 0; i < lastIndex; i++) {
if (countArr[i][0] == c) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
int a = countArr[foundIndex][1];
countArr[foundIndex][1] = (char) ++a;
} else {
countArr[lastIndex][0] = c;
countArr[lastIndex][1] = '1';
lastIndex++;
}
}
for (int i = 0; i < lastIndex; i++) {
System.out.println(countArr[i][0] + " " + countArr[i][1]);
}
}

How to Find the Longest Palindrome (java)

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.

Categories

Resources