Home > Enterprise >  avoid repetition in a Java array
avoid repetition in a Java array

Time:05-28

I'm trying to get my code to not only search if a char is present in an array, but also if it is present next to one another. So, if the input is hannah, the output should be hanah. It should only remove a char if it is next to the same char.

import java.util.*;   

public class test {   
    
  static void removeDuplicate(char str[], int length) {   
        
      int index = 0; 
  
      for (int i = 0; i < length; i  ) {   
             
          int j;   
          for (j = 0; j < i; j  ) {   
              if (str[i] == str[j])   
              {   
                  break;
              }   
          }   
    
          if (j == i)    
          {     
              str[index  ] = str[i];   
          }   
      } 
      System.out.println(String.valueOf(Arrays.copyOf(str, index)));   
  }   
  
 
  public static void main(String[] args)   {   
      String info = "hannahmontana";  
      char str[] = info.toCharArray();  
      int len = str.length;   
      removeDuplicate(str, len);   
  }   
}  

CodePudding user response:

This my solution

static String removeDuplicate(char str[], int length) {
    if (length == 0) return "";
    List<Character> list = new ArrayList<>();
    list.add(str[0]);
    for (int i = 1; i < length; i  ) {
        if (list.get(list.size() - 1) != str[i]) {
            list.add(str[i]);
        }
    }
    return list.stream()
            .map(Object::toString)
            .collect(Collectors.joining());
}

CodePudding user response:

You can do a recursive call here:

import java.util.*;   

public class test {   
    
  static String removeDuplicate(String input) {   
        
     if(input.length()<=1)
            return input;
        if(input.charAt(0)==input.charAt(1))
            return removeDuplicate(input.substring(1));
        else
            return input.charAt(0)   removeDuplicate(input.substring(1));
  }   
  
 
  public static void main(String[] args)   {   
      String info = "hannahmontana";  
      System.out.println(removeDuplicate(info));
  }   
}  

CodePudding user response:

You can also try RegExp. Maybe not so fast, but I consider it simpler and more readable.

static String removeDuplicate(char[] chars, int ignored) {
    return new String(chars).replaceAll("(.)\\1 ", "$1")
}

CodePudding user response:

Thanks for all the great answers! It turns out the solution was really simple. I just needed to change str[j] to str[i-1].

  • Related