Sam
Sam

Reputation: 25

Compress string longer than 2 - loops

Method to compress a string using java and loops. For example, if dc = "aabbbccaaaaba, then c = "aab3cca4ba" Here is what I have so far. Please help/guide. Thanks.

        int cnt = 1;
        String ans = "";
        for (int i = 0; i < dc.length(); i++) {
            if ((i < dc.length()) && (dc.charAt(i) == dc.charAt(i++)) && (dc.charAt(i) == dc.charAt(i+=2))){
                cnt++;
                ans = ans + dc.charAt(i) + cnt;
            }
            else
                ans = ans + dc.charAt(i);

            setC(ans);

Upvotes: 2

Views: 79

Answers (4)

Kushal Shinde
Kushal Shinde

Reputation: 725

Easiest Solution: - Only one for loop, Time Complexity - O(n)

public static void main(String[] args) {
    String str = "aabbbccaaaaba";
    char[] arr = str.toCharArray();
    int length = arr.length;


    StringBuilder sb = new StringBuilder();

    int count=1;

    for(int i=0; i<length; i++){
        if(i==length-1){
            sb.append(arr[i]+""+count);
            break;
        }

        if(arr[i]==arr[i+1]){
            count++;
        }
        else{
            sb.append(arr[i]+""+count);
            count=1;
        }
   }
    System.out.println(sb.toString());

} 

Upvotes: 0

 String dc = "aabbbccaaaaba";
 String and = "";
  int index = 0;
  int cnt = 2;
  While(dc.charAt(index) != null){
  int index1 = index + 1;
  char j = dc.charAt(index)
  While(j.equals(dc.charAt(index1)){
  cnt++;
  }
  //more code
  index++;
  } 

It's a little incomplete but if you follow the logic I think it's what you're looking for. I won't do your assignment for you.

Upvotes: 0

habitats
habitats

Reputation: 2461

Unless you're restricted to using for loops, I believe this would do the trick:

String sb = "";
for (int i = 0; i < dc.length(); i++) {
  char c = dc.charAt(i);
  int count = 1;
  while (i + 1 < dc.length() && (dc.charAt(i + 1)) == c) {
    count++;
    i++;
  }
  if (count > 1) {
    sb += count;
  }
  sb += c;
}

System.out.println(sb);

edit: Changed the example to use regular String instead of StringBuilder. However, I really advise against concatenating strings this way, especially if the string you're trying to compress is long.

Upvotes: 1

It might be easier to get what you want by using Sting.toCharArray().

Then manipulate the array accordingly.

Upvotes: 0

Related Questions