Home > database >  if the characters are same then consider it only once in java language
if the characters are same then consider it only once in java language

Time:06-20

So, i am basically new to java ,and there was this question on our programming test

input:ww:ii:pp:rr:oo

if the alphabets are same then consider only once

output:wipro

so i was able to remove the : from the input and was also able to separate them

my current output :[w,w,i,i,p,p,r,r,o,o]

but i am unable to consider the same characters only once,its been nearly 35 min :_(

    String txt="ww:ii:pp::rr:oo";
    String[] result= txt.split(":");
    System.out.println(Arrays.toString(result));//1
    String n11="";
    for(String str:result){
        n11  = str;
    }
    System.out.println(n11);//2
    result=n11.split("");
    System.out.println(Arrays.toString(result));//3
    String n12="";
    int i=0;
    for(String i:result){
        if(i.equals(i 1)){
            continue;
        }
        else {
            n12=n12 i;
        }
    }
    System.out.println(n12);//4
}

output

[ww, ii, pp, , rr, oo]
wwiipprroo
[w, w, i, i, p, p, r, r, o, o]
[nullw, nullw, nulli, nulli, nullp, nullp, nullr, nullr, nullo, nullo]

CodePudding user response:

Example:

 
public class GFG 
{
    /* Method to remove duplicates in a sorted array */
    static String removeDupsSorted(String str)
    {
    
        int res_ind = 1, ip_ind = 1;
          
        // Character array for removal of duplicate characters
        char arr[] = str.toCharArray();
          
        /* In place removal of duplicate characters*/
        while (ip_ind != arr.length)
        {
            if(arr[ip_ind] != arr[ip_ind-1])
            {
                arr[res_ind] = arr[ip_ind];
                res_ind  ;
            }
            ip_ind  ;
            
        }
      
        str = new String(arr);
        return str.substring(0,res_ind);
    }
       
    /* Method removes duplicate characters from the string
       This function work in-place and fills null characters
       in the extra space left */
    static String removeDups(String str)
    {
       // Sort the character array
       
       char temp[] = str.toCharArray();
       //Arrays.sort(temp);
       str = new String(temp);
         
       // Remove duplicates from sorted
       return removeDupsSorted(str);
    }
       
    // Driver Method
    public static void main(String[] args)
    {
        String str = "ww:ii:pp:rr:oo";
        String str1 =  str.replaceAll(":","");
        System.out.println(removeDups(str1));
    }
}

The source is taken from enter image description here

CodePudding user response:

Your first step is right. But, you have an error in i.equals(i 1) since i 1 isn't is the next element. You should iterate the array like this:

for (int i = 0; i < result.length - 1; i   ) {
    if (result[i].equals(result[i   1])) {
        // do the remove operation.
    }
}
  • Related