java - Compress string longer than 2 - loops -
java - Compress string longer than 2 - loops -
method compress string using java , loops. example, if dc = "aabbbccaaaaba, c = "aab3cca4ba" here have far. please help/guide. thanks.
int cnt = 1; string ans = ""; (int = 0; < 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);
unless you're restricted using loops, believe trick:
string sb = ""; (int = 0; < 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 illustration utilize regular string instead of stringbuilder. however, advise against concatenating strings way, if string you're trying compress long.
java string loops compression
Comments
Post a Comment