Remove Adjacent duplicate from a string keeping only one instance: java [duplicate] - java

This question already has answers here:
Java String Manipulation : Comparing adjacent Characters in Java
(12 answers)
Closed 7 years ago.
It is difficult to say in words so i ll use examples. Consider following inputs:-
Input String = AABBSTUUUX
Output String = ABSTUX
How to achieve this in java.

This should do it
String word = "AABBSTUUUX";
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
word.deleteCharAt(i + 1);
}
}
System.out.println(word);

Steps:
Scan the String from first to last
Add each character in in a char type variable temp
Compare each character to the temp except for the first (marked by index 0) character and delete the duplicate

An implementation similar to #Razib's solution above:
public String removeDupes(String in) {
if (in == null || in.length() <= 1) {
return in;
}
char lastLetter = in.charAt(0);
String out = String.valueOf(lastLetter);
for (int i = 1; i < in.length(); i++) {
char nextLetter = in.charAt(i);
if (nextLetter != lastLetter) {
out += nextLetter;
}
lastLetter = nextLetter;
}
return out;
}
Obviously, this is case-sensitive and will remove duplicate non-word characters as well.

Related

split regular expression string by main "or" operators

I just wanted to ask if there is an easy way to do this, before I start building a fully fletched regex interpreter or at least a quite big state machine, just to figure out what degree the or operators have and where to split. To make things clearer let's put a random example here:
String regex = "test (1|2|3)|testing\\||tester\\nNextLine[ab|]|(test)";
The result I want is the following, spliting the regex by its main or operators:
String[] result = { "test (1|2|3)", "testing\\|", "tester\\nNextLine[ab|]", "(test)" };
As mentioned I already have some ideas on complex solutions that involve going through the string char by char, skipping escaped characters, figuring out where all the brackets open and close, on what bracket-level that character is, adding the indices of those level 0 '|' characters to a list and splitting the string by those indices, but I am searching for a simple one- or two-liner
aka a more beautiful solution. Is there one?
To clarify this even further - I want all alternatives like this in one string array
UPDATE: Not the most beautiful version, but I actually implemented something like a state machine for this now:
private ArrayList<String> parseFilters(String regex) {
ArrayList<Integer> indices = new ArrayList<>();
Stack<Integer> brackets = new Stack<>();
int level = 0;
int bracketType = -1;
char lastChar = ' ';
char currentChar = ' ';
for (int i = 0; i < regex.length(); i++) {
currentChar = regex.charAt(i);
if (lastChar == '\\' || "^$?*+".indexOf(currentChar) >= 0)
;
else if (level == 0 && "|".indexOf(currentChar) >= 0)
indices.add(i + 1);
else if ((bracketType = "([{".indexOf(currentChar)) >= 0) {
brackets.push(bracketType);
level++;
} else if ((bracketType = ")]}".indexOf(currentChar)) >= 0) {
if (bracketType == brackets.peek()) {
brackets.pop();
level--;
}
}
lastChar = currentChar;
}
ArrayList<String> results = new ArrayList<>();
int lastIndex = 0;
for (int i : indices)
results.add(regex.substring(lastIndex, (lastIndex = i) - 1));
results.add(regex.substring(lastIndex));
return results;
}
Here is a proof of concept Java program splitting on double || and leaving single | untouched.
This would be more complicated to achieve with regex.
We have to double escape each pipe because the pattern is parsed twice, once when it is loaded into the variable and again when it is used as a pattern. \\|\\| is thus reduced to ||.
class split{
public static void main(String[] args){
String lineTest = "test (1|2|3)|testing\\||tester\\nNextLine[ab||]|(test)";
String separated[] =
lineTest.split("\\|\\|");
for ( int i = 0; i < separated.length;i++){
System.out.println( separated[i]);
}
}
}
The output is:
test (1|2|3)|testing\
tester\nNextLine[ab
]|(test)

How to check if a String can be formed from the characters of another String in Java?

A string is good if it can be formed by characters from chars. I want to return the sum of lengths of all good strings in words.
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Below is the code that I have written.
class Solution
{
public int countCharacters(String[] words, String chars)
{
int k = 0, count = 0;
Set<Character> set = new HashSet<>();
for(int i = 0; i < chars.length(); i++)
{
set.add(chars.charAt(i));
}
StringBuilder chrs = new StringBuilder();
for(Character ch : set)
{
chrs.append(ch);
}
for(int i = 0; i < words.length; i++)
{
char[] ch = words[i].toCharArray();
for(int j = 0; j < ch.length; j++)
{
if(chrs.contains("" + ch[j]))
{
k++;
}
}
if(k == words[i].length())
{
count+= k;
}
}
return count;
}
}
Output:
Line 24: error: cannot find symbol
if(chrs.contains("" + ch[j]))
Can someone help me? What am I doing wrong in accessing the character?
The issues which I noticed is you are using contains() to compare a String and a character. But the contains() method is a Java method to check if String contains another substring or not.
So you can solve this by converting the character to a string.
Ex 1:
if(chars.contains(Character.toString(ch[j]))){
k++;
} else {
}
Ex 2:
f(chars.contains(""+ch[j]))
{
k++;
} else {
}
Otherwise, You can compare if the string contains a char by using indexOf(). If the string isn't containing the char it return -1. Please refer bellow example.
Ex:
if(chars.indexOf(ch[j])!=-1){
k++;
} else {
}
contains tells you if a string is contained in another string. But in your case ch[j] is not a string but a char, so you can't use contains.
Instead, use indexOf, it returns -1 if the char is not present in the string.
the most simple way is
chars.contains("" + ch[i]);
Here, ch[j] is not a string but a char, so you can't use contains as you've done. Instead, make the following change.
chars.contains(String.valueOf(ch[j]));

How can i iterate a String and grab several data from there? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have this method:
public void separator(){
int count=0, i=0;
while (count == 0) {
if (track1result.charAt(i) != '^') {
char c = track1result.charAt(i);
number += c;
} else {
count++;
}
i++;
}
}
It's supposed to iterate a String until he reaches the ^ symbol, and that's great, and working so far, the problem is that i'm not sure how can i like keep going from there so i can get the string that's after the symbol and store it in another variable.
If you can give me ideas i would really appreciate it!
you can just split the String into array
String s1 = "hello^world";
String[] arr = s1.split("\\^");
String firstpart = arr[0];
String secondpart = arr[1];
System.out.println(firstpart+" "+secondpart);
Inside the else part add this:
if (i < track1result.length() - 1)
rest = track1result.substring(i + 1);
where rest is previously declared:
String rest = "";

Recursively computing all possible permutations of a string Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to compute all possible permutations of a given string using recursion in Java. However, I don't know what's wrong with my code.
Here's my algorithm:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
//base case
if (str.length() == 1)
perms.add(str);
else {
//loop over the string
for (int i = 0; i < str.length() - 1; i++) {
//make a subset of the string excluding the first char
String sub = str.substring(i + 1, str.length());
//compute permutations of the subset
ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
//add the first char that we excluded at the start of each permutations
for (String s : subPerms) {
s = str.charAt(i) + s;
perms.add(s);
}
}
}
return perms;
}
There are a few issues:
The following line: String sub = str.substring(i+1, str.length()); ignores the first character
The same line also treats anything after index i as a "block" of substring that is left unchanged, while in order to generate permutation we should insert the current (first) character in between any two characters of the rest of the string - and do that for each permutation
The line s = str.charAt(i) + s; repeats the same mistake in #2
Here's a suggested fix:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
if (str.length() == 1) {
perms.add(str);
} else {
String chr = str.substring(0,1);
String rest = str.substring(1);
ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
for (String s : subPerms) {
for (int j = 0; j <= s.length(); j++) {
String newPerm = s.substring(0,j) + chr + s.substring(j);
perms.add(newPerm);
}
}
}
return perms;
}

Additive operator used with char values produces different results [duplicate]

This question already has answers here:
The concatenation of chars to form a string gives different results
(5 answers)
Closed 7 years ago.
I am getting a strange return for the below block of code (sets of integer values):
public String doubleChar(String str) {
String answer = "";
for (int i = 0; i < str.length(); i++) {
answer = answer + (str.charAt(i) + str.charAt(i));
}
return answer;
}
Opposed to the correct output value (a duplication of the strings chars) when I remove the parentheses enclosing the str.chatAt method calls in the first statement line of the loop:
answer = answer + str.charAt(i) + str.charAt(i);
Any help is appreciated, could not track down online.
Thanks
In Java char is an integral type. It appears you wanted String concatenation (that is String addition). You could use
public String doubleChar(String str) {
String answer = "";
for (int i = 0; i < str.length(); i++) {
answer = answer + String.valueOf(str.charAt(i))
+ String.valueOf(str.charAt(i));
}
return answer;
}
or (my preference) a StringBuilder like
public String doubleChar(String str) {
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
sb.append(ch).append(ch);
}
return sb.toString();
}

Categories

Resources