Problem of the Day
A new programming or logic puzzle every Mon-Fri

Unique String

Happy Monday!

Let's start the week off right. Today's problem is to create a function that returns if a string contains all unique characters or not. For bonus points make the function case insensitive.

Permalink: http://problemotd.com/problem/unique-string/

Comments:

  • Anonymous - 10 years ago

    C#

    public static bool StringContainsOnlyUniqueCharacters(string s)
    {
        return s.Length == s.ToLowerInvariant().ToCharArray().Distinct().Count();
    }
    

    reply permalink

  • Erik - 10 years ago

    Using Rust 0.13:

    use std::collections::TreeSet;
    
    #[cfg(not(test))]
    fn main() {
    }
    
    fn is_string_unique(string: &str) -> bool {
        let mut set = TreeSet::new();
    
        for c in string.chars() {
            if !set.insert(c.to_lowercase()) {
                return false;
            }
        }
    
        true
    }
    
    #[test]
    fn is_string_unique_tests() {
        assert_eq!(is_string_unique("Hello"), false);
        assert_eq!(is_string_unique("HeLlo"), false);
        assert_eq!(is_string_unique("Helo"), true);
    }
    

    reply permalink

  • Max Burstein - 10 years ago

    Been meaning to play around with Rust. Looks cool

    reply permalink

  • Anonymous - 10 years ago

    Python ``` a = raw_input("Enter a string> ")

    a = a.lower()

    for character in a: if a.count(character) != 1: c = "Not unique" break c = "Unique"

    print c ```

    reply permalink

  • David - 9 years ago

    Using count() is probably more elegant:

    def is_unique(str_input):
      retval = True
      str_input = str_input.lower()
      for index in range(1,len(str_input)):
        if(str_input[index-1] in str_input[index:]):
          retval = False
          break
      return retval
    

    reply permalink

Content curated by @MaxBurstein