This question already has answers here:
How to sort String array by length using Arrays.sort()
(10 answers)
Closed 10 months ago.
INPUT: this is my string
OUTPUT: is my this string
I have to arrange words in a sentence according to their length and if two words have the same length then print them alphabetically (the first priority is length).
My incorrect code:
import java.util.Scanner;
class accordingtolength
{
void main()
{
String result="";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
String arr[]=str.split(" ");
int l=arr.length;
for(int i=0;i<l-1;i++)
{
String temp=arr[i]+" ";
String temp1=arr[i+1]+" ";
int a=temp.length();
int b=temp1.length();
if(a==b)
{
int c=temp.compareTo(temp1);
if(c>0)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
else if(a>b)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
System.out.println(result);
}
}
I know my code is incorrect so there is no need to attach the output.
Please help.
Perhaps this is what you were looking for. Using minimal external classes, this simply sorts the array of words in ascending order based on their length first and then alphabetically if those lengths are equal It uses a variant of what is known as a selection sort. It is a basic sort and quite often used as an introduction to sorting. But it is not very efficient.
read in the string and split based on spaces (I modified your regex to allow 1 or more spaces).
then use nested loops to iterate thru the list, comparing lengths.
if the word indexed by the outer loop (i) is longer than the word indexed by the inner loop (j), swap the words.
else if equal length compare words to each other and sort alphabetically (the String class implements the Comparable interface).
when both loops are finished, the array will be sorted in
then you can just iterate over the result building a string of words separated by spaces.
public class AccordingToLength {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String str = sc.nextLine();
String arr[] = str.split("\\s+");
for (int i = 0; i < arr.length-1; i++) {
int outer = arr[i].length();
for (int j = i + 1; j < arr.length; j++) {
int inner = arr[j].length();
if (outer > inner || outer == inner && arr[i].compareTo(arr[j]) > 0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
outer = inner; // outer has new length (what was just swapped)
}
}
}
String result = "";
for (String word : arr) {
result += word + " ";
}
System.out.println(result);
}
}
for input = "if a day now any easy when new test is done do den deed none"; this prints
a do if is any day den new now deed done easy none test when
There are multiple ways to solve this problem. The two most convenient ways are.
If you are allowed to use streams and comparator, then you can achieve it in a single line.
Arrays.stream(arr)
.sorted(Comparator
.comparing(String::length)
.thenComparing(Function.identity()))
.forEach(System.out::println);
Using Arrays.sort() to sort the actual array elements.
Arrays.sort(arr, (o1, o2) -> {
if (o1.length() > o2.length()) {
return 1;
} else if (o2.length() > o1.length()) {
return -1;
} else {
return o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(arr));
If you don't want to use java provided APIs and data structures, you can implement a different version of bubble sort.
boolean isSwapped;
for (int i = 0; i < arr.length - 1; i++) {
isSwapped = false;
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j].length() > arr[j + 1].length()
|| arr[j].length() == arr[j + 1].length() && arr[j].compareTo(arr[j + 1]) > 0) {
swap(arr, j, j + 1);
isSwapped = true;
}
}
if (!isSwapped)
break;
}
Related
this is a lab for class I'm trying to do. Here's the instructions:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
"Hello there
Hey
done"
the output is:
"ereht olleH
yeH"
And here's what I have right now:
public class LabProgram {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
String[] inputs = new String[100];
String input;
int i = 0;
while (true) {
input = scnr.nextLine();
if(input.equals("Done") || input.equals("done") || input.equals("d"))
break;
inputs[i] = input;
i++;
}
for (int j = 0; j < i; j++) {
int length = inputs[j].length();
String reverse = "";
for (int k = length - i; k >= 0; k--) {
reverse = reverse + inputs[j].charAt(k);
}
System.out.print("\n" + reverse);
}
}
}
Current output
What am I doing wrong??
Iterate through the array, and reverse elements at every index.
This solution is time consuming but does your job
for (int j = 0; j < inputs.lenght; j++) {
int length = inputs[j].length();
char a;
String rev = "";
for(int i =0; i< length; i++){
a = inputs[j].charAt(i);
rev = a + rev;
}
System.out.println(rev);
}
*Try to use StringBuilder And use method reverse -- #Artur Todeschini
To add to what Artur said, an ArrayList of StringBuilders could do the trick quite well:
for(StringBuilder nextEntry : stringBuilderList)
{
nextEntry.reverse();
}
The enhanced for-loop will go through each entry in the ArrayList, and the StringBuilder's reverse will change the order of the letters.
EDIT TO SHOW FORMATTING
ArrayList<StringBuilder> stringBuilderList= new ArrayList<>();
*note. given that this is for a lab, its probably for learning purposes and using built-in classes that does all the work for you are usually not the intended solution. -- #experiment unit 1998X
Try to use StringBuilder
And use method reverse
This is another "ArrayList and StringBuilder-less" version.
Create two Strings, one filled and one empty:
String nextString = stringArray[i],
template = new String();
Loop through the length of the String, adding the next character in from the end each time through.
int length = nextString.length() - 1;
for(int j = 0; j < length; j++)
{
template += nextString.charAt(length - j);
}
Add the whole String to the String array's index
stringArray[i] = template;
NOTE
This is an inner loop for a String array and is NOT complete code
I am trying to sort the digits of an Integer in descending order in JAVA but I am not allowed to use any array.
This was given to me as an assignment in class and below is a code that I tried but failed.
import java.util.Scanner;
class descend
{
public static void main(String args[])
{
int a=0,loc=0,parse=0,temp=0,big=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number");
a=scan.nextInt();
String s=Integer.toString(a);
int l=s.length();
for(int i=0;i<l;i++)
{
big=(int)(s.charAt(i));
loc=i;
for(int j=i+1;j<l;j++)
{
parse=(int)(s.charAt(j));
if(parse>big)
{
big = parse;
loc=j;
}
}
temp=parse;
s.charAt(i)=s.charAt(loc);
s.charAt(loc)=temp
}
System.out.print(s);
}
}
Here I get a syntax error at s.charAt(i)=s.charAt(loc); and s.charAt(loc)=temp; that a variable is required but a value is given.
Please help me out with this and I shall always be grateful to you.
Maybe the teacher want to test your knowledge about the new stream API. Or maybe he wants you to test your knowledge about Collections.sort() and LinkedList (which does not contain an internal array).
1.) Here is a solution with stream API:
int number = 52214;
String.valueOf(number).chars()
.sorted()
.map(Character::getNumericValue).forEach(System.out::print);
This will print out:
12245
2.) Here is a solution with collections:
List<Integer> list = new LinkedList<Integer>();
StringCharacterIterator iterator = new StringCharacterIterator(String.valueOf(number));
for (char c = iterator.first(); c != CharacterIterator.DONE; c = iterator.next())
{
list.add(Character.getNumericValue(c));
}
Collections.sort(list);
System.out.println("list=" + list);
This will print out:
list=[1, 2, 2, 4, 5]
String cannot be changed, only replaced, hence a = b; f(b); will never change a.
With 10 digits only, you could iterate, step through, from 0 upto 9 to have the sorting:
int number = ... // or String number
if (number == 0) { // or < 10
System.out.println(number);
} else {
for (int digit = 0; digit <= 9; ++digit) {
// While being able to remove the current digit:
for (;;) {
int scrapedNumber = numberWithoutDigitOnce(number, digit);
if (scrapedNumber == number) {
break;
}
number = scrapedNumber;
System.out.print(digit);
}
}
System.out.println();
}
int numberWithoutDigitOnce(int number, int digit) {
if (number % 10 == digit) {
return number / 10;
}
int n = numberWithoutDigitOnce(number/10, digit)*10 + (number % 10);
}
Zero is a special case.
A recursive solution, you find the highest digit in the String, add it to your output String, and remove it from your input String.
Repeat until your input String is empty.
Removing the character at a given index in a String can be achieve by concatenating the characters before the index and the ones after the index. (Or with a StringBuilder but I agree with the comments on the OP that it would be cheating to use a StringBuilder)
private static String sort(String digitsLeftToSort, String sortedString) {
if(digitsLeftToSort.length() == 0) { // no more character to sort
return sortedString;
} else {
// find the index of the highest digit
int index = findIndexOfHighestDigit(digitsLeftToSort);
// add the character at that index to your output String
sortedString += digitsLeftToSort.charAt(index);
// Remove it from your input String
digitsLeftToSort = digitsLeftToSort.substring(0, index) + digitsLeftToSort.substring(index+1);
// Recursive call with your new Strings
return sort(digitsLeftToSort, sortedString);
}
}
// This finds the index of the highest digit in the given String
private static int findIndexOfHighestDigit(String s) {
int highestDigitValue = -1;
int highestDigitIndex = -1;
int integerValue;
for(int i = 0; i< s.length(); i++) {
integerValue = Character.getNumericValue(s.charAt(i));
if(integerValue > highestDigitValue) {
highestDigitValue = integerValue;
highestDigitIndex = i;
}
}
return highestDigitIndex;
}
Then
String sortedString = sort("462375623478142", "");
System.out.println(sortedString);
Outputs
877665444332221
Sorry, But after applying so much effort, I figured it out.
int n=54321;char ch;
String s=Integer.toString(n);
int l= s.length();
for(int i=48;i<=57;i++) //ascii values from 0 - 9
{
for(int j=0;j<l;j++)
{
ch=s.charAt(j);
if(ch==(char)i) // checking if a digit equals a number
{
System.out.print(ch);
}
}
}
It sorts the digits in ascending order. To sort in descending order we should use
for(int i=57;i>=48;i--)
The problem is
how to get the maximum repeated String in an array using only operations on the arrays in java?
so i got into this question in a test and couldn't figure it out.
lets suppose we have an array of string.
str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }
in str1 abbey was maximum repeated, so abbey should be returned and
in str2 abbey and caley both have same number of repetitions and hence we take maximum alphabet as the winner and is returned(caley here).
c > a
so i tried till
import java.util.*;
public class test {
static String highestRepeated(String[] str) {
int n = str.length, num = 0;
String temp;
String str2[] = new String[n / 2];
for (int k = 0;k < n; k++) { // outer comparision
for (int l = k + 1; l < n; l++) { // inner comparision
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
}
// I'm stuck here
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter how many votes");
int n = sc.nextInt();
String[] str = new String[n];
for (int i = 0; i < n; i++) {
Str[i] = sc.nextLine();
}
String res = highestRepeated(str);
System.out.println(res + " is the winner");
}
}
so, how should i take the count of occurrence of each string with and attach it with the string itself.
All this, without using a map and any hashing but just by using arrays?
Here is a (unpolished) solution:
static String highestRepeated(String[] str) {
String[] sorted = Arrays.copyOf(str, str.length);
Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
String currentString = sorted[0];
String bestString = sorted[0];
int maxCount = 1;
int currentCount = 1;
for (int i = 1 ; i < sorted.length ; i++) {
if (currentString.equals(sorted[i])) {
currentCount++;
} else {
if (maxCount < currentCount) {
maxCount = currentCount;
bestString = currentString;
}
currentString = sorted[i];
currentCount = 1;
}
}
if (currentCount > maxCount) {
return currentString;
}
return bestString;
}
Explanation:
Sort the array from highest to lowest lexicographically. That's what Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder()); does. we sort in this order because you want the largest string if there are multiple strings with the same number of repeats.
Now we can just count the strings by looping through the array. We don't need a hash map or anything because we know that there will be no more of a string in the rest of the array when we encounter a different string.
currentString is the string that we are currently counting the number of repeats of, using currentCount. maxCount is the number of occurrence of the most repeated string - bestString - that we have currently counted.
The if statement is pretty self-explanatory: if it is the same string, count it, otherwise see if the previous string we counted (currentCount) appears more times than the current max.
At the end, I check if the last string being counted is more than max. If the last string in the array happens to be the most repeated one, bestString won't be assigned to it because bestString is only assigned when a different string is encountered.
Note that this algorithm does not handle edge cases like empty arrays or only one element arrays. I'm sure you will figure that out yourself.
another version
static String lastMostFrequent(String ... strs) {
if (strs.length == 0) return null;
Arrays.sort(strs);
String str = strs[0];
for (int longest=0, l=1, i=1; i<strs.length; i++) {
if (!strs[i-1].equals(strs[i])) { l=1; continue; }
if (++l < longest) continue;
longest = l;
str = strs[i];
}
return str;
}
change in
if (++l <= longest) continue;
for firstMostFrequent
you can't use == to check if two strings are the same.
try using this instead:
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
I'm trying to write a program that reads a string of text and prints all digrams in this text and their frequencies. A digram is a sequence of two characters. The program prints digrams sorted based on frequencies (in descending
order).
Example of input: park car at the parking lot
Corresponding output: ar:3 pa:2 rk:2 at:1 ca:1 he:1 in:1 ki:1 lo:1 ng:1 ot:1 th:1
I have this implementation but it only works for every character in the string. How would I implement this for every digram?
import java.util.Scanner;
public class Digrams {
public static void main(String args[]) {
int ci, i, j, k, l=0;
String str, str1;
char c, ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
str=scan.nextLine();
i=str.length();
for(c='A'; c<='z'; c++)
{
k=0;
for(j=0; j<i; j++)
{
ch = str.charAt(j);
if(ch == c)
{
k++;
}
}
if(k>0)
{
System.out.println("" +c +": " +k);
}
}
}
}
I know you've already got perfect answers and much much better than this, but I was wondering if I can sort the result in descending order without the help of Collections Class, it may be of help, or a new idea.
import java.util.ArrayList;
import java.util.Scanner;
public class Digrams{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Insert The Sentence");
String []sentence = in.nextLine().split(" "); // split the input according to the spaces and put them in array
//get all digrams
ArrayList<String> allDigrams = new ArrayList<String>(); // ArrayList to contain all possible digrams
for(int i=0; i<sentence.length; i++){ // do that for every word
for(int j=0; j<sentence[i].length(); j++){ // cycle through each char at each index in the sentence array
String oneDigram= "";
if(j<sentence[i].length()-1){
oneDigram += sentence[i].charAt(j); // append the char and the following char
oneDigram += sentence[i].charAt(j+1);
allDigrams.add(oneDigram); // add the one diagram to the ArrayList
}
}
}
// isolate digrams and get corresponding frequencies
ArrayList<Integer> frequency = new ArrayList<Integer>(); // for frequencies
ArrayList<String> digrams = new ArrayList<String>(); //for digrams
int freqIndex=0;
while(allDigrams.size()>0){
frequency.add(freqIndex,0);
for(int j=0; j<allDigrams.size(); j++){ // compare each UNIQUE digram with the rest of the digrams to find repetition
if(allDigrams.get(0).equalsIgnoreCase(allDigrams.get(j))){
frequency.set(freqIndex, frequency.get(freqIndex)+1); // increment frequency
}
}
String dig = allDigrams.get(0); // record the digram temporarily
while(allDigrams.contains(dig)){ // now remove all repetition from the allDigrams ArrayList
allDigrams.remove(dig);
}
digrams.add(dig); // add the UNIQUE digram
freqIndex++; // move to next index for the following digram
}
// sort result in descending order
// compare the frequency , if equal -> the first char of digram, if equal -> the second char of digram
// and move frequencies and digrams at every index in each ArrayList accordingly
for (int i = 0 ; i < frequency.size(); i++){
for (int j = 0 ; j < frequency.size() - i - 1; j++){
if (frequency.get(j) < frequency.get(j+1) ||
((frequency.get(j) == frequency.get(j+1)) && (digrams.get(j).charAt(0) > digrams.get(j+1).charAt(0))) ||
((digrams.get(j).charAt(0) == digrams.get(j+1).charAt(0)) && (digrams.get(j).charAt(1) > digrams.get(j+1).charAt(1)))){
int swap = frequency.get(j);
String swapS = digrams.get(j);
frequency.set(j, frequency.get(j+1));
frequency.set(j+1, swap);
digrams.set(j, digrams.get(j+1));
digrams.set(j+1, swapS);
}
}
}
//final result
String sortedResult="";
for(int i=0; i<frequency.size(); i++){
sortedResult+=digrams.get(i) + ":" + frequency.get(i) + " ";
}
System.out.println(sortedResult);
}
}
Input
park car at the parking lot
Output
ar:3 pa:2 rk:2 at:1 ca:1 he:1 in:1 ki:1 lo:1 ng:1 ot:1 th:1
The way to do it is to check for every 2 letter combination, and look for those instead. You can do this by using a double for-loop, like so:
public static void main(String args[]) {
int ci, i, j, k, l=0;
String str, str1, result, subString;
char c1, c2, ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
str=scan.nextLine();
i=str.length();
for(c1='A'; c1<='z'; c1++)
{
for(c2='A'; c2<='z'; c2++) {
result = new String(new char[]{c1, c2});
k = 0;
for (j = 0; j < i-1; j++) {
subString = str.substring(j, j+2);
if (result.equals(subString)) {
k++;
}
}
if (k > 0) {
System.out.println("" + result + ": " + k);
}
}
}
}
This also means you have to compare Strings, rather than comparing chars. This of course means the .equals() function needs to be used, rather than the == operator, since String is an object in Java.
Result for me was:
ar: 3 at: 1 ca: 1 he: 1 in: 1 ki: 1 lo: 1 ng: 1 ot: 1 pa: 2 rk: 2 th: 1
Here's how you do it in one line:
Map<String, Long> digramFrequencies = Arrays
.stream(str
.replaceAll("(?<!^| ).(?! |$)", "$0$0") // double letters
.split(" |(?<=\\G..)")) // split into digrams
.filter(s -> s.length() > 1) // discard short terms
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
See live demo.
This works by:
doubling all letters not at start/end of words, eg "abc defg" becomes "abbc deeffg"
splitting into pairs, re-starting splits at start of word
discarding short terms (eg words like "I" and "a")
counting frequencies
This should help:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
String str = scan.nextLine();
ArrayList<String> repetition = new ArrayList<String>();
ArrayList<String> digrams = new ArrayList<String>();
String digram;
for(int i = 0; i < str.length() - 1; i++) {
digram = str.substring(i, i + 2);
if(repetition.contains(digram) || digram.contains(" ") || digram.length() < 2)
continue;
int occurances = (str.length() - str.replace(digram, "").length()) / 2;
occurances += (str.replaceFirst(".*?(" + digram.charAt(0) + "+).*", "$1").length() - 1) / 2;
digrams.add(digram + ":" + occurances);
repetition.add(digram);
}
Collections.sort(digrams, (s1, s2) -> s1.substring(3, 4).compareTo(s2.substring(3, 4)));
System.out.println(digrams);
}
If you don't want to use jdk8 then let me know.
I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:
public void bigesttstring(String str){
String[] wordsArray=str.split(" ");
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
}
}
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:
int count=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
count++;
}
}
and for display other longest strings i have this code:
int k=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
k++;
}
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
other[o]=wordsArray[i];
o++;
}
}
I allowed to use this functions:
char char At(int i);
int ComoareTo(String another string);
boolean endsWith(String suffix);
int indexof();
int indexof(String str);
String substring();
char[] toCharArray();
String lowercase();
And want another code like this for shortest strings.
You have written
if(wordsArray[i].length()>maxsize)
For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4.
Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be
if(wordsArray[i].length()>=maxsize)
you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.
You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.
package OtherPeoplesCode;
public class string {
public static void main(String[] args) {
bigeststring("wall hall to wall hall fall be");
}
public static void bigeststring(String str){
String[] wordsArray=str.split(" ");
String[] biggestWordsArray = new String[wordsArray.length];
int x = 0;
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
for(int y = 0; y <= biggestWordsArray.length -1; y++){
biggestWordsArray[y] = "";
}
}
else if(maxsize==wordsArray[i].length()){
biggestWordsArray[x] = wordsArray[i];
x++;
}
}
if(biggestWordsArray[0].equals("")){
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
else if(!(biggestWordsArray[0].equals(""))){
System.out.println("TIE!");
for(int y = 0; y <= biggestWordsArray.length -1; y++){
if(!(biggestWordsArray[y].equals(""))){
System.out.print("Word #" + y + " is ");
System.out.println(biggestWordsArray[y]);
}
}
}
}
}
EDIT: This is the working code, sorry about the delay.
Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.
One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):
loop through the list of words, and find out the length of the longest word and number of words with such length
Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want
in psuedo code:
String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
if word is longer then maxLen {
maxLen = word's length
maxLenOccurence = 1;
}
else if word's length is equals to maxLen {
maxLenOccurence ++
}
}
// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
else if word's length is equals to maxLen {
for i = 0 to maxLenWordList length {
if (maxLenWordList[i] == word)
break
if (maxLenWordList[i] == null
maxLenWordList[i] = word
}
}
//4
foreach maxLenWord in maxLenWordList {
count = 0
foreach word in wordList {
if maxLenWord == word
count ++
}
display "Max sized word is "+ maxLenWord + " with size " + count
}
Another way doesn't involve other data structure is:
Have the word list
Sort the word list first by length then by the literal value
First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Also you can use this;
String[] allLongestStrings(String[] inputArray) {
List<String> list = new ArrayList<String>();
int max = 0;
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n > max) {
max = n;
}
}
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n == max) {
list.add(s.toString());
}
}
return list.toArray(new String[list.size()]);
}