Java: Print a unique character in a string
up vote
5
down vote
favorite
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (Stringargs){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
java string character unique
add a comment |
up vote
5
down vote
favorite
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (Stringargs){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
java string character unique
What is the expected output for 'nreena' ?
– developer
Nov 30 '16 at 23:10
1
Buteis a repeat, and you're still getting it. Is the desired outputra?
– Gendarme
Nov 30 '16 at 23:10
Anyways, I'd do something likechar array = test.toCharArray();and then loop througharrayfor each letter intestand if there are no matches, dotemp = temp + test.charAt(i);.
– Gendarme
Nov 30 '16 at 23:16
Yes, the desired output would be "ra".
– Dextra
Nov 30 '16 at 23:16
Once you've added a character, you are not removing the existing one on finding its multiple occurrences.
– nullpointer
Nov 30 '16 at 23:29
add a comment |
up vote
5
down vote
favorite
up vote
5
down vote
favorite
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (Stringargs){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
java string character unique
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (Stringargs){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
java string character unique
java string character unique
edited Nov 30 '16 at 23:18
asked Nov 30 '16 at 23:07
Dextra
25114
25114
What is the expected output for 'nreena' ?
– developer
Nov 30 '16 at 23:10
1
Buteis a repeat, and you're still getting it. Is the desired outputra?
– Gendarme
Nov 30 '16 at 23:10
Anyways, I'd do something likechar array = test.toCharArray();and then loop througharrayfor each letter intestand if there are no matches, dotemp = temp + test.charAt(i);.
– Gendarme
Nov 30 '16 at 23:16
Yes, the desired output would be "ra".
– Dextra
Nov 30 '16 at 23:16
Once you've added a character, you are not removing the existing one on finding its multiple occurrences.
– nullpointer
Nov 30 '16 at 23:29
add a comment |
What is the expected output for 'nreena' ?
– developer
Nov 30 '16 at 23:10
1
Buteis a repeat, and you're still getting it. Is the desired outputra?
– Gendarme
Nov 30 '16 at 23:10
Anyways, I'd do something likechar array = test.toCharArray();and then loop througharrayfor each letter intestand if there are no matches, dotemp = temp + test.charAt(i);.
– Gendarme
Nov 30 '16 at 23:16
Yes, the desired output would be "ra".
– Dextra
Nov 30 '16 at 23:16
Once you've added a character, you are not removing the existing one on finding its multiple occurrences.
– nullpointer
Nov 30 '16 at 23:29
What is the expected output for 'nreena' ?
– developer
Nov 30 '16 at 23:10
What is the expected output for 'nreena' ?
– developer
Nov 30 '16 at 23:10
1
1
But
e is a repeat, and you're still getting it. Is the desired output ra?– Gendarme
Nov 30 '16 at 23:10
But
e is a repeat, and you're still getting it. Is the desired output ra?– Gendarme
Nov 30 '16 at 23:10
Anyways, I'd do something like
char array = test.toCharArray(); and then loop through array for each letter in test and if there are no matches, do temp = temp + test.charAt(i);.– Gendarme
Nov 30 '16 at 23:16
Anyways, I'd do something like
char array = test.toCharArray(); and then loop through array for each letter in test and if there are no matches, do temp = temp + test.charAt(i);.– Gendarme
Nov 30 '16 at 23:16
Yes, the desired output would be "ra".
– Dextra
Nov 30 '16 at 23:16
Yes, the desired output would be "ra".
– Dextra
Nov 30 '16 at 23:16
Once you've added a character, you are not removing the existing one on finding its multiple occurrences.
– nullpointer
Nov 30 '16 at 23:29
Once you've added a character, you are not removing the existing one on finding its multiple occurrences.
– nullpointer
Nov 30 '16 at 23:29
add a comment |
14 Answers
14
active
oldest
votes
up vote
6
down vote
accepted
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
1
this is efficient!
– Xlee
Dec 1 '16 at 0:19
@Xlee, thank you
– lmiguelvargasf
Dec 1 '16 at 1:54
Thank you so much!
– Dextra
Dec 5 '16 at 15:29
add a comment |
up vote
2
down vote
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
1
it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repatedtest.charAt(i)more than once.
– lmiguelvargasf
Nov 30 '16 at 23:40
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
– nullpointer
Nov 30 '16 at 23:41
add a comment |
up vote
2
down vote
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
Hipster, man :+1:
– Xlee
Dec 1 '16 at 0:14
add a comment |
up vote
2
down vote
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String args) {
String s="aabcddkkbghff";
String cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
add a comment |
up vote
1
down vote
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
add a comment |
up vote
1
down vote
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"t"+count);
}
}
public static void main(String args) {
uniqueValue(input);
}
add a comment |
up vote
0
down vote
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
add a comment |
up vote
0
down vote
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
1
Can you add some explanation? Thanks!
– MLavrentyev
Jul 6 '17 at 19:19
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
– shanbhagsv
Sep 24 at 10:10
add a comment |
up vote
0
down vote
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
add a comment |
up vote
0
down vote
I use this way to get unique chars
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
add a comment |
up vote
0
down vote
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
– WhatsThePoint
Mar 12 at 11:09
add a comment |
up vote
0
down vote
public class UniqueCharactersInString {
public static void main(String args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Code only answers are really discouraged. To help future readers, please explain what you are doing too!
– itsmysterybox
Nov 8 at 4:48
add a comment |
up vote
0
down vote
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
add a comment |
up vote
0
down vote
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string.
In the second line I am looking for characters repetitive once.
add a comment |
14 Answers
14
active
oldest
votes
14 Answers
14
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
6
down vote
accepted
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
1
this is efficient!
– Xlee
Dec 1 '16 at 0:19
@Xlee, thank you
– lmiguelvargasf
Dec 1 '16 at 1:54
Thank you so much!
– Dextra
Dec 5 '16 at 15:29
add a comment |
up vote
6
down vote
accepted
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
1
this is efficient!
– Xlee
Dec 1 '16 at 0:19
@Xlee, thank you
– lmiguelvargasf
Dec 1 '16 at 1:54
Thank you so much!
– Dextra
Dec 5 '16 at 15:29
add a comment |
up vote
6
down vote
accepted
up vote
6
down vote
accepted
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
answered Nov 30 '16 at 23:35
lmiguelvargasf
10.6k976100
10.6k976100
1
this is efficient!
– Xlee
Dec 1 '16 at 0:19
@Xlee, thank you
– lmiguelvargasf
Dec 1 '16 at 1:54
Thank you so much!
– Dextra
Dec 5 '16 at 15:29
add a comment |
1
this is efficient!
– Xlee
Dec 1 '16 at 0:19
@Xlee, thank you
– lmiguelvargasf
Dec 1 '16 at 1:54
Thank you so much!
– Dextra
Dec 5 '16 at 15:29
1
1
this is efficient!
– Xlee
Dec 1 '16 at 0:19
this is efficient!
– Xlee
Dec 1 '16 at 0:19
@Xlee, thank you
– lmiguelvargasf
Dec 1 '16 at 1:54
@Xlee, thank you
– lmiguelvargasf
Dec 1 '16 at 1:54
Thank you so much!
– Dextra
Dec 5 '16 at 15:29
Thank you so much!
– Dextra
Dec 5 '16 at 15:29
add a comment |
up vote
2
down vote
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
1
it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repatedtest.charAt(i)more than once.
– lmiguelvargasf
Nov 30 '16 at 23:40
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
– nullpointer
Nov 30 '16 at 23:41
add a comment |
up vote
2
down vote
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
1
it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repatedtest.charAt(i)more than once.
– lmiguelvargasf
Nov 30 '16 at 23:40
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
– nullpointer
Nov 30 '16 at 23:41
add a comment |
up vote
2
down vote
up vote
2
down vote
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
edited Nov 30 '16 at 23:42
answered Nov 30 '16 at 23:37
nullpointer
36.4k1071143
36.4k1071143
1
it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repatedtest.charAt(i)more than once.
– lmiguelvargasf
Nov 30 '16 at 23:40
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
– nullpointer
Nov 30 '16 at 23:41
add a comment |
1
it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repatedtest.charAt(i)more than once.
– lmiguelvargasf
Nov 30 '16 at 23:40
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
– nullpointer
Nov 30 '16 at 23:41
1
1
it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repated
test.charAt(i) more than once.– lmiguelvargasf
Nov 30 '16 at 23:40
it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repated
test.charAt(i) more than once.– lmiguelvargasf
Nov 30 '16 at 23:40
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
– nullpointer
Nov 30 '16 at 23:41
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
– nullpointer
Nov 30 '16 at 23:41
add a comment |
up vote
2
down vote
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
Hipster, man :+1:
– Xlee
Dec 1 '16 at 0:14
add a comment |
up vote
2
down vote
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
Hipster, man :+1:
– Xlee
Dec 1 '16 at 0:14
add a comment |
up vote
2
down vote
up vote
2
down vote
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
edited Dec 1 '16 at 0:56
answered Nov 30 '16 at 23:56
Bohemian♦
292k61410548
292k61410548
Hipster, man :+1:
– Xlee
Dec 1 '16 at 0:14
add a comment |
Hipster, man :+1:
– Xlee
Dec 1 '16 at 0:14
Hipster, man :+1:
– Xlee
Dec 1 '16 at 0:14
Hipster, man :+1:
– Xlee
Dec 1 '16 at 0:14
add a comment |
up vote
2
down vote
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String args) {
String s="aabcddkkbghff";
String cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
add a comment |
up vote
2
down vote
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String args) {
String s="aabcddkkbghff";
String cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
add a comment |
up vote
2
down vote
up vote
2
down vote
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String args) {
String s="aabcddkkbghff";
String cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String args) {
String s="aabcddkkbghff";
String cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
edited Oct 4 '17 at 20:12
Matthew Ciaramitaro
937724
937724
answered Oct 4 '17 at 19:07
rajesh
212
212
add a comment |
add a comment |
up vote
1
down vote
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
add a comment |
up vote
1
down vote
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
add a comment |
up vote
1
down vote
up vote
1
down vote
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
edited Apr 30 at 9:34
answered Apr 24 at 8:06
Soudipta Dutta
12913
12913
add a comment |
add a comment |
up vote
1
down vote
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"t"+count);
}
}
public static void main(String args) {
uniqueValue(input);
}
add a comment |
up vote
1
down vote
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"t"+count);
}
}
public static void main(String args) {
uniqueValue(input);
}
add a comment |
up vote
1
down vote
up vote
1
down vote
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"t"+count);
}
}
public static void main(String args) {
uniqueValue(input);
}
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"t"+count);
}
}
public static void main(String args) {
uniqueValue(input);
}
edited Jul 25 at 16:01
Robert
4,0371251106
4,0371251106
answered Jul 25 at 15:37
Dana
111
111
add a comment |
add a comment |
up vote
0
down vote
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
add a comment |
up vote
0
down vote
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
add a comment |
up vote
0
down vote
up vote
0
down vote
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
answered Nov 30 '16 at 23:40
Gendarme
1,22821325
1,22821325
add a comment |
add a comment |
up vote
0
down vote
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
1
Can you add some explanation? Thanks!
– MLavrentyev
Jul 6 '17 at 19:19
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
– shanbhagsv
Sep 24 at 10:10
add a comment |
up vote
0
down vote
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
1
Can you add some explanation? Thanks!
– MLavrentyev
Jul 6 '17 at 19:19
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
– shanbhagsv
Sep 24 at 10:10
add a comment |
up vote
0
down vote
up vote
0
down vote
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
answered Jul 6 '17 at 18:49
shanbhagsv
507
507
1
Can you add some explanation? Thanks!
– MLavrentyev
Jul 6 '17 at 19:19
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
– shanbhagsv
Sep 24 at 10:10
add a comment |
1
Can you add some explanation? Thanks!
– MLavrentyev
Jul 6 '17 at 19:19
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
– shanbhagsv
Sep 24 at 10:10
1
1
Can you add some explanation? Thanks!
– MLavrentyev
Jul 6 '17 at 19:19
Can you add some explanation? Thanks!
– MLavrentyev
Jul 6 '17 at 19:19
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
– shanbhagsv
Sep 24 at 10:10
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
– shanbhagsv
Sep 24 at 10:10
add a comment |
up vote
0
down vote
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
add a comment |
up vote
0
down vote
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
add a comment |
up vote
0
down vote
up vote
0
down vote
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
answered Dec 4 '17 at 13:17
anchouksey
111
111
add a comment |
add a comment |
up vote
0
down vote
I use this way to get unique chars
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
add a comment |
up vote
0
down vote
I use this way to get unique chars
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
add a comment |
up vote
0
down vote
up vote
0
down vote
I use this way to get unique chars
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
I use this way to get unique chars
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
edited Jan 12 at 0:46
answered Jan 12 at 0:31
Parviz Makari
180110
180110
add a comment |
add a comment |
up vote
0
down vote
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
– WhatsThePoint
Mar 12 at 11:09
add a comment |
up vote
0
down vote
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
– WhatsThePoint
Mar 12 at 11:09
add a comment |
up vote
0
down vote
up vote
0
down vote
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
edited Mar 12 at 11:19
answered Mar 12 at 10:48
RathanaKumar
215
215
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
– WhatsThePoint
Mar 12 at 11:09
add a comment |
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
– WhatsThePoint
Mar 12 at 11:09
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
– WhatsThePoint
Mar 12 at 11:09
Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
– WhatsThePoint
Mar 12 at 11:09
add a comment |
up vote
0
down vote
public class UniqueCharactersInString {
public static void main(String args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Code only answers are really discouraged. To help future readers, please explain what you are doing too!
– itsmysterybox
Nov 8 at 4:48
add a comment |
up vote
0
down vote
public class UniqueCharactersInString {
public static void main(String args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Code only answers are really discouraged. To help future readers, please explain what you are doing too!
– itsmysterybox
Nov 8 at 4:48
add a comment |
up vote
0
down vote
up vote
0
down vote
public class UniqueCharactersInString {
public static void main(String args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
public class UniqueCharactersInString {
public static void main(String args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
answered Nov 8 at 4:44
Zulu
1
1
Code only answers are really discouraged. To help future readers, please explain what you are doing too!
– itsmysterybox
Nov 8 at 4:48
add a comment |
Code only answers are really discouraged. To help future readers, please explain what you are doing too!
– itsmysterybox
Nov 8 at 4:48
Code only answers are really discouraged. To help future readers, please explain what you are doing too!
– itsmysterybox
Nov 8 at 4:48
Code only answers are really discouraged. To help future readers, please explain what you are doing too!
– itsmysterybox
Nov 8 at 4:48
add a comment |
up vote
0
down vote
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
add a comment |
up vote
0
down vote
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
add a comment |
up vote
0
down vote
up vote
0
down vote
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
answered Nov 8 at 4:56
BHARAT Bhasin
156
156
add a comment |
add a comment |
up vote
0
down vote
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string.
In the second line I am looking for characters repetitive once.
add a comment |
up vote
0
down vote
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string.
In the second line I am looking for characters repetitive once.
add a comment |
up vote
0
down vote
up vote
0
down vote
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string.
In the second line I am looking for characters repetitive once.
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string.
In the second line I am looking for characters repetitive once.
edited Nov 13 at 21:39
answered Nov 13 at 21:18
ptaq
11
11
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40899915%2fjava-print-a-unique-character-in-a-string%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What is the expected output for 'nreena' ?
– developer
Nov 30 '16 at 23:10
1
But
eis a repeat, and you're still getting it. Is the desired outputra?– Gendarme
Nov 30 '16 at 23:10
Anyways, I'd do something like
char array = test.toCharArray();and then loop througharrayfor each letter intestand if there are no matches, dotemp = temp + test.charAt(i);.– Gendarme
Nov 30 '16 at 23:16
Yes, the desired output would be "ra".
– Dextra
Nov 30 '16 at 23:16
Once you've added a character, you are not removing the existing one on finding its multiple occurrences.
– nullpointer
Nov 30 '16 at 23:29