data compression
جمعه, ۱۶ آبان ۱۳۹۹، ۰۱:۲۵ ق.ظ
package ir.javacup.cmp; public class Compression { public String compress(String data) { if(data==null) return null; if(data.isEmpty()) return ""; String t=""; int rep=1; char b=data.charAt(0); for(int j=1;j<data.length();j++) { if(samechar(data.charAt(j),b)) rep++; else { if(rep>2) { t=t+rep+makelow(b); } else { t+=(data.substring(j-rep,j)); } rep=1; b=data.charAt(j); } } if(rep>2) { t=t+rep+makelow(b); } else { t+=(data.substring(data.length()-rep,data.length())); } return t; } boolean samechar(char c,char t) { return makelow(c)==makelow(t); } char makelow(char c) { if(c>='a' && c<='z') return c; else if(c>='A' && c<='Z') return (char)(c-'A'+'a'); return c; } public static void main(String[] args) { System.out.println(new Compression().compress("")); //prints: abb63753c System.out.println(new Compression().compress("aabddc")); //prints: aabddc System.out.println(new Compression().compress("AaaABbbcdefGG")); //prints: 4a3bcdefGG } }
۹۹/۰۸/۱۶