There are a couple of improvements that can be made, mostly readability improvements as I believe your solution is quite efficient.
- Format your code with proper indentation and spacing
Indentation is important for readability, so is spacing; don't be afraid to throw in plenty of whitespace if it makes things easier to read. Notice how I indented on every bracket level and put in white space in between some lines and put spaces in for loops etc.
public static String uniqueValues(String str) {
char[] arr = str.toCharArray();
int[] result = NumberOfOccurences.numberOfOccurencesOfLetters(arr);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < result.length; i++) {
if(result[i]==1) {
sb.append((char)(i+97));
sb.append(" ");
}
}
return sb.toString();
}
//in the other class i wrote this method
public static int[] numberOfOccurencesOfLetters(char[] arr) {
int[] result = new int[26];
int num;
for(int i = 0; i < arr.length; i++) {
num = (arr[i]-97);
result[num]++;
}
return result;
}
- Pass in a string to
numberOfOccurencesOfLetters
instead of a char[].
Assuming you'll be using this method mostly of strings, you should pass in a string and do the conversion inside numberOfOccurencesOfLetters
rather than before calling it every time.
public static int[] numberOfOccurencesOfLetters(String str) {
char[] arr = str.toCharArray();
int[] result = new int[26];
int num;
for(int i = 0; i < arr.length; i++) {
num = (arr[i]-97);
result[num]++;
}
return result;
}
- Declare variables closest to where they're used and limit their scope as much as possible.
For example int num;
can exist only within the for loop instead of the whole function scope as we only use it inside the for loop.
for(int i = 0; i < arr.length; i++) {
int num = (arr[i]-97);
result[num]++;
}
- Return a
HashMap
instead of int[]
for numberOfOccurencesOfLetters
.
Google what is a map in Java. This sacrifices some speed, but you'll get much more readable code with a return type that's easier to manipulate. Also, you won't be limited to the 26
characters that you have now and you'll be able to have upper-case letters and special characters as well.
This is how your whole code would look like with this implementation. If it doesn't compile I'll fix it when I get home.
import java.util.HashMap;
public static String uniqueValues(String str) {
HashMap<Character, Integer> result = NumberOfOccurences.numberOfOccurencesOfLetters(str);
StringBuilder sb = new StringBuilder();
for (Character key : result.keySet()) {
sb.append(key);
sb.append(" ");
}
return sb.toString();
}
public static Map<Character, Integer> numberOfOccurencesOfLetters(String str) {
HashMap<Character, Integer> hmap = new HashMap<Character, Integer>();
char[] arr = str.toCharArray();
for(int i = 0; i < arr.length; i++) {
Character key = arr[i];
hmap.put(key, hmap.getOrDefault(key, 0) + 1);
}
return hmap;
}
97
is a magic number. I would suggest using'a'
instead because that clarifies your intent. \$\endgroup\$