How to resolve the algorithm Determine if a string has all unique characters step by step in the Groovy programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Determine if a string has all unique characters step by step in the Groovy programming language

Table of Contents

Problem Statement

Given a character string   (which may be empty, or have a length of zero characters):

Use (at least) these five test values   (strings):

Show all output here on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Determine if a string has all unique characters step by step in the Groovy programming language

Source code in the groovy programming language

class StringUniqueCharacters {
    static void main(String[] args) {
        printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions")
        printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------")
        for (String s : ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]) {
            processString(s)
        }
    }

    private static void processString(String input) {
        Map<Character, Integer> charMap = new HashMap<>()
        char dup = 0
        int index = 0
        int pos1 = -1
        int pos2 = -1
        for (char key : input.toCharArray()) {
            index++
            if (charMap.containsKey(key)) {
                dup = key
                pos1 = charMap.get(key)
                pos2 = index
                break
            }
            charMap.put(key, index)
        }
        String unique = (int) dup == 0 ? "yes" : "no"
        String diff = (int) dup == 0 ? "" : "'" + dup + "'"
        String hex = (int) dup == 0 ? "" : Integer.toHexString((int) dup).toUpperCase()
        String position = (int) dup == 0 ? "" : pos1 + " " + pos2
        printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length(), unique, diff, hex, position)
    }
}


  

You may also check:How to resolve the algorithm Abbreviations, easy step by step in the PHP programming language
You may also check:How to resolve the algorithm Count occurrences of a substring step by step in the FunL programming language
You may also check:How to resolve the algorithm Hash from two arrays step by step in the Objeck programming language
You may also check:How to resolve the algorithm Elementary cellular automaton/Random number generator step by step in the F# programming language
You may also check:How to resolve the algorithm Matrix multiplication step by step in the Mathematica/Wolfram Language programming language