Skip to content

Instantly share code, notes, and snippets.

@Shivamy2
Last active January 27, 2021 11:25
Show Gist options
  • Save Shivamy2/efd9facb4bed27d774b570574db6d0eb to your computer and use it in GitHub Desktop.
Save Shivamy2/efd9facb4bed27d774b570574db6d0eb to your computer and use it in GitHub Desktop.
Added Java and Cpp Code
// Java Code
import java.util.HashMap;
import java.util.Map;
// Time Complexity: O(n)
// Space Complexity: O(n)
// where n = length of string
class Solution {
public static final int MAX_UNICODE = 65_535;
public static boolean checkWhetherStringIsUnique(String string) {
Map<Character, Boolean> characters = new HashMap<>();
int start = 0;
while(start < string.length()) {
int ascii = string.charAt(start)+0;
if(ascii > MAX_UNICODE) {
System.out.println("INVALID VALUE");
break;
} else {
if(string.charAt(start) == ' ') start++; //ignoring whitespace
else {
// checking if character is present in map or not
if(characters.containsKey(string.charAt(start))) return false;
else {
characters.put(string.charAt(start), false);
start++;
}
}
}
}
return true;
}
}
class Scratch {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.checkWhetherStringIsUnique("Shivam"));
System.out.println(solution.checkWhetherStringIsUnique("Competative Programming"));
System.out.println(solution.checkWhetherStringIsUnique("qwertyui asdf ghjk zxcv bnm"));
}
}
// C++ Code
#include<bits/stdc++.h>
using namespace std;
#define MAX_UNICODE 65535
// Time Complexity: O(n)
// Space Complexity: O(n)
// where n = length of string
bool checkWhetherStringIsUnique(string);
int main() {
if(checkWhetherStringIsUnique("Competative Programming")) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
if(checkWhetherStringIsUnique("QWERTY UIOP LKJH FDSA ZXCV")) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
bool checkWhetherStringIsUnique(string value) {
unordered_map<char,bool> checking;
for(auto chars : value) {
int ascii = chars+0;
if(ascii > MAX_UNICODE) {
cout << "INVALID VALUE" << endl;
break;
} else {
if(chars == ' ') continue; //ignoring whitespace
else {
// checking if character is present in map or not
if(checking.find(chars) != checking.end()) return false;
else {
checking[chars] == false;
}
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment