Unique characters from string - java

I am trying to print all the unique characters from a string but I am not getting proper output. Also, I want to check if someone enters integer in string, I want to print Invalid String. How can I achieve this?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] ch = new char[20];
System.out.println("Enter the sentence:");
String sent = sc.nextLine().replaceAll(" ", "");
int count = 0;
for (int i = 0; i < sent.length(); i++) {
int j = (sent.length() - 1);
count = 0;
while (j > i) {
if (sent.charAt(j) == sent.charAt(i)) {
sent = deleteCharAt(sent, i);
sent = deleteCharAt(sent, j - 1);
break;
}
j--;
}
}
for (int i = 0; i < sent.length(); i++) {
System.out.println(sent.charAt(i));
}
}
private static String deleteCharAt(String strValue, int index) {
return strValue.substring(0, index) + strValue.substring(index + 1);
}
Enter the sentence:
java is good object oriented programming language
a
v
i
s
o
d
b
c
r
e
e
d
p
g
m
m
n
l
u

You are probably going to want to use a Set. These data structures are like Lists, except:
They do not have an ordering (meaning you cant call set.get(3))
They do not allow duplicates
You can think of them as a Map without any values.
If you have a String and you want to get all the unique chars from it. The steps are as follows:
String string = "hello"; // 4 unique characters
Set<Character> uniqueChars = new HashSet<>(); // create an empty set to put the unique chars into
// split into char[]
char[] chars = string.toCharArray();
Arrays.stream(chars).forEach(c -> {
// the following code will be run once for every char in the array
uniqueChars.add(c);
// adding the same char twice does not insert it twice
});
This can be written more concisely as:
String string = "hello";
Set<Character> uniqueChars = new HashSet<>();
Arrays.stream(string.toCharArray()).forEach(uniqueChars::add); // using a Java 8 method reference
If you want to reject any char that is a numerical digit, you can use the following line:
boolean containsDigit = Arrays.stream(string.toCharArray())
.filter(Character::isDigit) // filter out all the non digit characters
.findAny() // check if there are any remaining
.isPresent();

It would be more efficient and easier to read code to use a HashSet:
HashSet<Character> h = new HashSet<Character>();
for (int i = 0; i <= (sent.length() - 1); i++)
h.add(sent.charAt(i));
Iterator<Character> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());

To avoid duplicate you can use a Set: is a collection that doesn't allow duplicates. You have to use a specific implementation of that interface, such as HashSet. You can do something like this:
public class UniqueChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence:");
String withoutSpaces = sc.nextLine();
withoutSpaces = "asc34csf"; // mock example
Set<Character> goodChars = new HashSet<>();
String sent = withoutSpaces.replaceAll(" ", "");
int count = 0;
for (int i = 0; i < sent.length(); i++) {
char currChar = sent.charAt(i);
// do not add a character if is a digit
if(Character.isDigit(currChar))
System.out.println("Digit!");
else
goodChars.add(currChar); // add a character only if not present
}
String output = "";
for (Character character : goodChars) {
output += character; // concat in a single output string
}
System.out.println(output);
}
So you simply jump characters that are digits, if it's a character it'll be added to the collection (and the Set manages internally the fact that if it's a duplicate, it will not be added), then concat the elements of the Set in a single String.
You can find more information about HashSet in the Java documentation.

You can write your code something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] alpha = new int[26];
System.out.println("Enter the sentence:");
String sent = sc.nextLine().replaceAll(" ", "");
for (int i = 0; i < sent.length(); i++) {
int temp = sent[i] - 'a';
if (temp >= 0 && temp <= 25) {
alpha[temp] = 1;
} else {
System.out.println("Invalid String");
return;
}
}
for (int i = 0; i < 26; i++) {
if (alpha[i] == 1)
System.out.println((char) (i + 'a'));
}
}
This uses an array of length 26 as the workaround if you don't want to use any SET like data structure.
This code can bring you problem if your sentence have capital letters as well. You can avoid that problem by using toLowercase like function just before the loop.

Related

Reverse String characters in java

Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();

Count a specified number

I would like to ask you a question, I want to count how many times a specified number is in a given numer (long) from the user and print it as an int.
Could you please help me with this code?
Apologize for my english.
Example:
< number specified = 4; number given = 34434544; result = 5. >
Check whether the least-significant digit is equal to the digit you are searching for; then divide by ten and check again; keep going until you reach zero.
int cnt = 0;
while (value != 0) {
if (value % 10 == digit) ++cnt;
value /= 10;
}
Where you are trying to count the occurrences of digit in the big number value.
If you're using Java 8:
long count = String.valueOf(givenNumber).chars()
.filter(c -> c == (specifiedNumber + '0'))
.count();
Make a Scanner to get input from System.in. Then, iterate through the String returned by turning it into a char[]. Then analyse each char and count original characters. Probably use a Map<Character, Integer> for this. For each element in the Map, iterate by one if it is in the Map. Query the Map for your desired character and print the result when finished.
public static void main(String[] args) {
CharacterFinder cf = new CharacterFinder();
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
Map<Character, Integer> resultsMap = cf.countChar(input);
System.out.println(resultsMap.get('g'));
}
// Note that 'null' means that it does not appear and if it is null, you ought print 0 instead.
// Also note that this method is case sensitive.
private Map<Character, Integer> countChar(String input) {
Map<Character, Integer> resultsMap = new HashMap<Character, Integer>();
for (int i = 0; i < input.length(); i++) {
Character element = input.charAt(i);
if (resultsMap.containsKey(element)) {
Integer cCount = resultsMap.get(element);
resultsMap.put(element, cCount + 1);
} else {
resultsMap.put(element, 1);
}
}
return resultsMap;
}
Well, unless you already know the char you want. In that case, analyse for that exact char.
public static void main(String[] args) {
CharacterFinder cf = new CharacterFinder();
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
// Call counting method and print
System.out.println(cf.countChar(input, '5'));
}
// Counting method
private int countChar(String input, char c) {
int x = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == c) {
x++;
}
}
return x;
}

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

How to use split a string into character array without special characters?

Scanner _in = new Scanner(System.in);
System.out.println("Enter an Equation of variables");
String _string = _in.nextLine();
char[] cArray = _string.toCharArray();
I want to remove the symbols "+,=" and I want to remove any repeating variables.
so far I have:
for(int i = 0; i < cArray.length; i++){
if(cArray[i].equals(+)|| cArray[i].equals(=)){
cArray[i] = null;
}
}
However, I dont know how to condence the array to remove any gaps and I don't know how to remove repeating characters, I think I am making this harder than it needs to be
You can use:
_string.replaceAll("[+,=]","");
This sounds like a good use for regular expressions:
String result = _string.replaceAll("[+=]", "");
Here, the [+=] is a character class that consists of + and =. You can add other characters as required.
Try the next:
public static void main(String[] args) {
String input = "a+a+b=c+d-a";
char[] cArray = input.replaceAll("[-+=]", "") // gaps
.replaceAll("(.)(?=.*\\1)", "") // repeating
.toCharArray();
System.out.println(Arrays.toString(cArray));
}
Output:
[b, c, d, a]
Or you can se another array, like this:
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char [] cArray = s.toCharArray();
int count = 0;
char [] cArray2 = new char[cArray.length];
for (int i = 0; i < cArray.length; i++){
if (cArray[i] != '+' || cArray[i] != '='){
cArray2[count++] = cArray[i];
}
}
for (int i = 0; i < count; i++){
boolean repeated = false;
for (int j = i + 1; j < count; j++){
if (cArray2[i] == cArray2[j]){
repeated = true;
break;
}
}
if (!repeated){
//do what you want
}
}
You can extend LinkedHashSet (Which enforces uniqueness and retains order). Override the add() function to not accept any characters that you don't want to use. Then put the contents in a char array.
public static char[] toCharArray(String str) {
// Here I am anonymously extending LinkedHashSet
Set<Character> characters = new LinkedHashSet<Character>() {
// Overriding the add method
public boolean add(Character character) {
if (!character.toString().matches("[\\+=]")) {
// character is not '+' or '='
return super.add(character);
}
// character is '+' or '='
return false;
}
};
// Adding characters from str to the set.
// Duplicates, '+'s, and '='s will not be added.
for (int i = 0; i < str.length(); i++) {
characters.add(str.charAt(i));
}
// Put Characters from set into a char[] and return.
char[] arrayToReturn = new char[characters.size()];
int i = 0;
for (Character c : characters) {
arrayToReturn[i++] = c;
}
return arrayToReturn;
}

Removing duplicates from a String in Java

I am trying to iterate through a string in order to remove the duplicates characters.
For example the String aabbccdef should become abcdef
and the String abcdabcd should become abcd
Here is what I have so far:
public class test {
public static void main(String[] args) {
String input = new String("abbc");
String output = new String();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < output.length(); j++) {
if (input.charAt(i) != output.charAt(j)) {
output = output + input.charAt(i);
}
}
}
System.out.println(output);
}
}
What is the best way to do this?
Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates. Something like:
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
System.out.println(sb.toString());
Using Stream makes it easy.
noDuplicates = Arrays.asList(myString.split(""))
.stream()
.distinct()
.collect(Collectors.joining());
Here is some more documentation about Stream and all you can do with
it :
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
The 'description' part is very instructive about the benefits of Streams.
Try this simple solution:
public String removeDuplicates(String input){
String result = "";
for (int i = 0; i < input.length(); i++) {
if(!result.contains(String.valueOf(input.charAt(i)))) {
result += String.valueOf(input.charAt(i));
}
}
return result;
}
I would use the help of LinkedHashSet. Removes dups (as we are using a Set, maintains the order as we are using linked list impl). This is kind of a dirty solution. there might be even a better way.
String s="aabbccdef";
Set<Character> set=new LinkedHashSet<Character>();
for(char c:s.toCharArray())
{
set.add(Character.valueOf(c));
}
Create a StringWriter. Run through the original string using charAt(i) in a for loop. Maintain a variable of char type keeping the last charAt value. If you iterate and the charAt value equals what is stored in that variable, don't add to the StringWriter. Finally, use the StringWriter.toString() method and get a string, and do what you need with it.
Here is an improvement to the answer by Dave.
It uses HashSet instead of the slightly more costly LinkedHashSet, and reuses the chars buffer for the result, eliminating the need for a StringBuilder.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
Set<Character> present = new HashSet<>();
int len = 0;
for (char c : chars)
if (present.add(c))
chars[len++] = c;
System.out.println(new String(chars, 0, len)); // abcdeftz
Java 8 has a new String.chars() method which returns a stream of characters in the String. You can use stream operations to filter out the duplicate characters like so:
String out = in.chars()
.mapToObj(c -> Character.valueOf((char) c)) // bit messy as chars() returns an IntStream, not a CharStream (which doesn't exist)
.distinct()
.map(Object::toString)
.collect(Collectors.joining(""));
String input = "AAAB";
String output = "";
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index % input.length()) != input
.charAt((index + 1) % input.length())) {
output += input.charAt(index);
}
}
System.out.println(output);
but you cant use it if the input has the same elements, or if its empty!
Code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra array is not:
import java.util.*;
public class Main{
public static char[] removeDupes(char[] arr){
if (arr == null || arr.length < 2)
return arr;
int len = arr.length;
int tail = 1;
for(int x = 1; x < len; x++){
int y;
for(y = 0; y < tail; y++){
if (arr[x] == arr[y]) break;
}
if (y == tail){
arr[tail] = arr[x];
tail++;
}
}
return Arrays.copyOfRange(arr, 0, tail);
}
public static char[] bigArr(int len){
char[] arr = new char[len];
Random r = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+[]{}|;:',.<>/?`~";
for(int x = 0; x < len; x++){
arr[x] = alphabet.charAt(r.nextInt(alphabet.length()));
}
return arr;
}
public static void main(String args[]){
String result = new String(removeDupes(new char[]{'a', 'b', 'c', 'd', 'a'}));
assert "abcd".equals(result) : "abcda should return abcd but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'a', 'a'}));
assert "a".equals(result) : "aaaa should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'c', 'a'}));
assert "abc".equals(result) : "abca should return abc but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'b', 'b'}));
assert "ab".equals(result) : "aabb should return ab but it returns: " + result;
result = new String(removeDupes(new char[]{'a'}));
assert "a".equals(result) : "a should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'b', 'a'}));
assert "ab".equals(result) : "abba should return ab but it returns: " + result;
char[] arr = bigArr(5000000);
long startTime = System.nanoTime();
System.out.println("2: " + new String(removeDupes(arr)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Program took: " + duration + " nanoseconds");
System.out.println("Program took: " + duration/1000000000 + " seconds");
}
}
How to read and talk about the above code:
The method called removeDupes takes an array of primitive char called arr.
arr is returned as an array of primitive characters "by value". The arr passed in is garbage collected at the end of Main's member method removeDupes.
The runtime complexity of this algorithm is O(n) or more specifically O(n+(small constant)) the constant being the unique characters in the entire array of primitive chars.
The copyOfRange does not increase runtime complexity significantly since it only copies a small constant number of items. The char array called arr is not stepped all the way through.
If you pass null into removeDupes, the method returns null.
If you pass an empty array of primitive chars or an array containing one value, that unmodified array is returned.
Method removeDupes goes about as fast as physically possible, fully utilizing the L1 and L2 cache, so Branch redirects are kept to a minimum.
A 2015 standard issue unburdened computer should be able to complete this method with an primitive char array containing 500 million characters between 15 and 25 seconds.
Explain how this code works:
The first part of the array passed in is used as the repository for the unique characters that are ultimately returned. At the beginning of the function the answer is: "the characters between 0 and 1" as between 0 and tail.
We define the variable y outside of the loop because we want to find the first location where the array index that we are looking at has been duplicated in our repository. When a duplicate is found, it breaks out and quits, the y==tail returns false and the repository is not contributed to.
when the index x that we are peeking at is not represented in our repository, then we pull that one and add it to the end of our repository at index tail and increment tail.
At the end, we return the array between the points 0 and tail, which should be smaller or equal to in length to the original array.
Talking points exercise for coder interviews:
Will the program behave differently if you change the y++ to ++y? Why or why not.
Does the array copy at the end represent another 'N' pass through the entire array making runtime complexity O(n*n) instead of O(n) ? Why or why not.
Can you replace the double equals comparing primitive characters with a .equals? Why or why not?
Can this method be changed in order to do the replacements "by reference" instead of as it is now, "by value"? Why or why not?
Can you increase the efficiency of this algorithm by sorting the repository of unique values at the beginning of 'arr'? Under which circumstances would it be more efficient?
public class RemoveRepeated4rmString {
public static void main(String[] args) {
String s = "harikrishna";
String s2 = "";
for (int i = 0; i < s.length(); i++) {
Boolean found = false;
for (int j = 0; j < s2.length(); j++) {
if (s.charAt(i) == s2.charAt(j)) {
found = true;
break; //don't need to iterate further
}
}
if (found == false) {
s2 = s2.concat(String.valueOf(s.charAt(i)));
}
}
System.out.println(s2);
}
}
public static void main(String a[]){
String name="Madan";
System.out.println(name);
StringBuilder sb=new StringBuilder(name);
for(int i=0;i<name.length();i++){
for(int j=i+1;j<name.length();j++){
if(name.charAt(i)==name.charAt(j)){
sb.deleteCharAt(j);
}
}
}
System.out.println("After deletion :"+sb+"");
}
import java.util.Scanner;
public class dublicate {
public static void main(String... a) {
System.out.print("Enter the String");
Scanner Sc = new Scanner(System.in);
String st=Sc.nextLine();
StringBuilder sb=new StringBuilder();
boolean [] bc=new boolean[256];
for(int i=0;i<st.length();i++)
{
int index=st.charAt(i);
if(bc[index]==false)
{
sb.append(st.charAt(i));
bc[index]=true;
}
}
System.out.print(sb.toString());
}
}
To me it looks like everyone is trying way too hard to accomplish this task. All we are concerned about is that it copies 1 copy of each letter if it repeats. Then because we are only concerned if those characters repeat one after the other the nested loops become arbitrary as you can just simply compare position n to position n + 1. Then because this only copies things down when they're different, to solve for the last character you can either append white space to the end of the original string, or just get it to copy the last character of the string to your result.
String removeDuplicate(String s){
String result = "";
for (int i = 0; i < s.length(); i++){
if (i + 1 < s.length() && s.charAt(i) != s.charAt(i+1)){
result = result + s.charAt(i);
}
if (i + 1 == s.length()){
result = result + s.charAt(i);
}
}
return result;
}
String str1[] ="Hi helloo helloo oooo this".split(" ");
Set<String> charSet = new LinkedHashSet<String>();
for (String c: str1)
{
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (String character : charSet)
{
sb.append(character);
}
System.out.println(sb.toString());
I think working this way would be more easy,,,
Just pass a string to this function and the job is done :) .
private static void removeduplicate(String name)
{ char[] arr = name.toCharArray();
StringBuffer modified =new StringBuffer();
for(char a:arr)
{
if(!modified.contains(Character.toString(a)))
{
modified=modified.append(Character.toString(a)) ;
}
}
System.out.println(modified);
}
public class RemoveDuplicatesFromStingsMethod1UsingLoops {
public static void main(String[] args) {
String input = new String("aaabbbcccddd");
String output = "";
for (int i = 0; i < input.length(); i++) {
if (!output.contains(String.valueOf(input.charAt(i)))) {
output += String.valueOf(input.charAt(i));
}
}
System.out.println(output);
}
}
output: abcd
You can't. You can create a new String that has duplicates removed. Why aren't you using StringBuilder (or StringBuffer, presumably)?
You can run through the string and store the unique characters in a char[] array, keeping track of how many unique characters you've seen. Then you can create a new String using the String(char[], int, int) constructor.
Also, the problem is a little ambiguousβ€”does β€œduplicates” mean adjacent repetitions? (In other words, what should happen with abcab?)
Oldschool way (as we wrote such a tasks in Apple ][ Basic, adapted to Java):
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++){
for (j=i+1;j<str.length();j++){
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed non-unique symbols: " + str);
Here is another logic I'd like to share. You start comparing from midway of the string length and go backward.
Test with:
input = "azxxzy";
output = "ay";
String removeMidway(String input){
cnt = cnt+1;
StringBuilder str = new StringBuilder(input);
int midlen = str.length()/2;
for(int i=midlen-1;i>0;i--){
for(int j=midlen;j<str.length()-1;j++){
if(str.charAt(i)==str.charAt(j)){
str.delete(i, j+1);
midlen = str.length()/2;
System.out.println("i="+i+",j="+j+ ",len="+ str.length() + ",midlen=" + midlen+ ", after deleted = " + str);
}
}
}
return str.toString();
}
Another possible solution, in case a string is an ASCII string, is to maintain an array of 256 boolean elements to denote ASCII character appearance in a string. If a character appeared for the first time, we keep it and append to the result. Otherwise just skip it.
public String removeDuplicates(String input) {
boolean[] chars = new boolean[256];
StringBuilder resultStringBuilder = new StringBuilder();
for (Character c : input.toCharArray()) {
if (!chars[c]) {
resultStringBuilder.append(c);
chars[c] = true;
}
}
return resultStringBuilder.toString();
}
This approach will also work with Unicode string. You just need to increase chars size.
Solution using JDK7:
public static String removeDuplicateChars(final String str){
if (str == null || str.isEmpty()){
return str;
}
final char[] chArray = str.toCharArray();
final Set<Character> set = new LinkedHashSet<>();
for (char c : chArray) {
set.add(c);
}
final StringBuilder sb = new StringBuilder();
for (Character character : set) {
sb.append(character);
}
return sb.toString();
}
String str = "eamparuthik#gmail.com";
char[] c = str.toCharArray();
String op = "";
for(int i=0; i<=c.length-1; i++){
if(!op.contains(c[i] + ""))
op = op + c[i];
}
System.out.println(op);
public static String removeDuplicateChar(String str){
char charArray[] = str.toCharArray();
StringBuilder stringBuilder= new StringBuilder();
for(int i=0;i<charArray.length;i++){
int index = stringBuilder.toString().indexOf(charArray[i]);
if(index <= -1){
stringBuilder.append(charArray[i]);
}
}
return stringBuilder.toString();
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveDuplicacy
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any word : ");
String s = br.readLine();
int l = s.length();
char ch;
String ans=" ";
for(int i=0; i<l; i++)
{
ch = s.charAt(i);
if(ch!=' ')
ans = ans + ch;
s = s.replace(ch,' '); //Replacing all occurrence of the current character by a space
}
System.out.println("Word after removing duplicate characters : " + ans);
}
}
public static void main(String[] args) {
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++)
{
for (j=1;j<str.length();j++)
{
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed String: " + str);
}
This is improvement on solution suggested by #Dave. Here, I am implementing in single loop only.
Let's reuse the return of set.add(T item) method and add it simultaneously in StringBuffer if add is successfull
This is just O(n). No need to make a loop again.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
StringBuilder sb = new StringBuilder();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
if(charSet.add(c) ){
sb.append(c);
}
}
System.out.println(sb.toString()); // abcdeftz
Simple solution is to iterate through the given string and put each unique character into another string(in this case, a variable result ) if this string doesn't contain that particular character.Finally return result string as output.
Below is working and tested code snippet for removing duplicate characters from the given string which has O(n) time complexity .
private static String removeDuplicate(String s) {
String result="";
for (int i=0 ;i<s.length();i++) {
char ch = s.charAt(i);
if (!result.contains(""+ch)) {
result+=""+ch;
}
}
return result;
}
If the input is madam then output will be mad.
If the input is anagram then output will be angrm
Hope this helps.
Thanks
For the simplicity of the code- I have taken hardcore input, one can take input by using Scanner class also
public class KillDuplicateCharInString {
public static void main(String args[]) {
String str= "aaaabccdde ";
char arr[]= str.toCharArray();
int n = arr.length;
String finalStr="";
for(int i=0;i<n;i++) {
if(i==n-1){
finalStr+=arr[i];
break;
}
if(arr[i]==arr[i+1]) {
continue;
}
else {
finalStr+=arr[i];
}
}
System.out.println(finalStr);
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
String str = "";
char c;
for(int i = 0; i < s.length(); i++)
{
c = s.charAt(i);
str = str + c;
s = s.replace(c, ' ');
if(i == s.length() - 1)
{
System.out.println(str.replaceAll("\\s", ""));
}
}
}
package com.st.removeduplicate;
public class RemoveDuplicate {
public static void main(String[] args) {
String str1="shushil",str2="";
for(int i=0; i<=str1.length()-1;i++) {
int count=0;
for(int j=0;j<=i;j++) {
if(str1.charAt(i)==str1.charAt(j))
count++;
if(count >1)
break;
}
if(count==1)
str2=str2+str1.charAt(i);
}
System.out.println(str2);
}
}

Categories