'Calculate independent letter in a String

Write a program that, when given a string representing a carpet, outputs its price. Example: abacx Answer: 20 (length 5 multiplied by 4 different types)

    int length = str.length();
    String letters = "";
    String str2 = " " + str;
    for (int i = 1; i < str2.length(); i++) {
        for (int j = 0; j < str.length(); j++) {
            
        }
        if (str2.charAt(i) != str2.charAt(i-1) ) {
            letters += str2.charAt(i);
            
        }
        
    }
    int length2 = letters.length();
    int price = length * length2;
    System.out.println(price);
   

Here's what I have so far. These are the test cases 3a)qiraat 3b)cdefghijklmnopqrstuwxyz 3c)warrior 3d)supercalifragilisticexpialidocious



Solution 1:[1]

If I understand your question correctly, you want to multiply the number of characters the String contains by the unique number of characters it has.

The first one is trivial, it is simply myString.length().

In order to get the second one, you can use a list of characters like this:

    List<Character> uniqueChars = new ArrayList<>();
    for (int i = 0; i < myString.lengt(); i ++) {
        char c = myString.charAt(i);
        if (!uniqueChars.contains(c)) {
            uniqueChars.add(c);
        }
    }

    int price = myString.length() * uniqueChars.size();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WeinSim