161k views
2 votes
Java:

numUnique returns the number of unique values the list
Precondition: the list is not empty and is sorted from low to high.
{ your solution can assume this is true }

For full credit, your solution must go through the list exactly once. Your solution may not call any other functions.

Examples:

["abcdef"].numUnique() == 6

["aaabcd"].numUnique() == 4

["bccddee"].numUnique() == 4

["abcddd"].numUnique() == 4

["a"].numUnique() == 1

_____________________________________________

public int numUnique() {

//Fix this

1 Answer

4 votes

Answer:

import java.util.*;

public class work {

// function for counting unique character

public static int numUnique(String input) {

boolean[] list = new boolean[Character.MAX_VALUE];

for (int i = 0; i < input.length(); i++) {

list[input.charAt(i)] = true;

}

int count = 0;

for (int i = 0; i <list.length; i++) {

if (list[i] == true){

count++;

}

}

return count;

}

public static void main(String args[])

{

List<String>list=new ArrayList<>(); // creatng array list of type string

list.add("abcdef");

list.add("aaabcd");

list.add("bccddee");

list.add("abcddd");

list.add("a");

for(String str:list)

{

// for printing the results

System.out.println("given string : "+ str+" , number of unique values :"+numUnique(str));

}

}

}

Step-by-step explanation:

User Neil Masson
by
6.1k points