id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

orion.a.smith@gmail.com apcsa-loops > apcsaLoopsCharacterVariety
prev  |  next  |  chance

Given an input String, return the number of different characters present in the String. Thus, "abc" and "aaabbbc" will both return 3 because they all contain only 'a', 'b', 'c'. Precondition: str will only contain visible characters from the original ASCII subset (i.e. between values of 32 and 127).


HINT: There are multiple ways to approach this problem.

First, given the precondition above, what if you started with something like the following?
boolean[] counts = new boolean[128]; // index positions 0-127, all elements start false
char firstChar = str.charAt(0);
int charValue = (int)firstChar; // converts firstChar into a number

The precondition tells us that charValue >= 0 and charValue <= 127 right?  Could you use that information to flip some of the array elements?  Could you then figure out how many of those elements have been flipped?

Or, you can use a loop like
while(str.length() > 0) {
  String first = str.substring(0,1); // extract first character
  // do something with the first character
  str = str.substring(1); // chop off first character for next iteration
}
to keep looping as long as str has more characters to examine. You might consider using the replace() method of the String class to eliminate every character matching the first character of str from the output. Using replace looks like this:
str.replace("a","") // evaluates to a version of str with no 'a' characters
Also remember that a loop such as the one above will continue to operate even if the object referenced by str is replaced with a String with fewer characters...

apcsaLoopsCharacterVariety("abc") → 3
apcsaLoopsCharacterVariety("aaabbbc") → 3
apcsaLoopsCharacterVariety("z") → 1

...Save, Compile, Run (ctrl-enter)

public int apcsaLoopsCharacterVariety(String str) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 230

Copyright Nick Parlante 2017 - privacy