Problem description

Implement an algorithm that determines whether all characters of a string are different. Here we require that no additional storage structures be allowed.

Given a string, return a bool, true for all different characters, false for the same characters.

Ensure that the characters in the string are ASCII characters.

The value contains a maximum of 3000 characters.

Their thinking

Four:

  1. ASCII characters. In ASCII characters, the printable character range is32The Spaces to126the~, a total of95A character.
  2. All different. That is, characters in a string are not duplicated.
  3. No additional storage structures are allowed.
  4. The value is less than or equal to 3000. This condition is useless because there are only 95 printable ASCII characters, and if a string is longer than 95 characters, there must be duplicates or non-printable characters.

Since additional storage structures are not allowed, there is no good low-time complexity algorithm, and only a more violent way to search one by one.

The complete code

Methods a

Use the strings.count () function to assist:

The string.count () function counts the number of non-overlapping instances of substr in S.

If substr is an empty string, strings.Count returns the Unicode code point in s+1.

func isUniqueString(s string) bool {
        if strings.Count(s, "") > 95 {
                return false
        }
        for _, v := range s {
                if v < 32 || v > 126 {
                        return false
                }
                if strings.Count(s, string(v)) > 1 {
                        return false}}return true
}
Copy the code

Method 2

Use the strings.lastIndex () function to assist:

Strings.lastindex () returns the index of the last instance of substr in S.

If substr does not exist in s, -1 is returned.

func isUniqueString(s string) bool {
        if strings.Count(s, "") > 95 {
                return false
        }
        for index, v := range s {
                if v < 32 || v > 126 {
                        return false
                }
                if strings.LastIndex(s, string(v)) ! = index {return false}}return true
}
Copy the code