Java压缩字符串

我需要创建一个接收String的方法,并返回一个String。

输入:AAABBBBCC

Ex输出:3A4B2C

嗯,这是非常尴尬的,我无法在今天的采访中做到这一点(我申请了一个初级职位),现在,在家里尝试我做了一些静态工作,我的意思是,不使用循环这是一种无用的但我不知道我是否没有得到足够的睡眠或其他什么,但我无法弄清楚我的for循环应该是什么样子。 这是代码:

public static String Comprimir(String texto){ StringBuilder objString = new StringBuilder(); int count; char match; count = texto.substring(texto.indexOf(texto.charAt(1)), texto.lastIndexOf(texto.charAt(1))).length()+1; match = texto.charAt(1); objString.append(count); objString.append(match); return objString.toString(); } 

感谢您的帮助,我正在努力提高我的逻辑技能。

循环通过字符串记住你上次看到的内容。 每次看到相同的字母数。 当您看到一封新信件时,将您计算的数字放在输出上,并将新字母设置为您上次看到的字母。

 String input = "AAABBBBCC"; int count = 1; char last = input.charAt(0); StringBuilder output = new StringBuilder(); for(int i = 1; i < input.length(); i++){ if(input.charAt(i) == last){ count++; }else{ if(count > 1){ output.append(""+count+last); }else{ output.append(last); } count = 1; last = input.charAt(i); } } if(count > 1){ output.append(""+count+last); }else{ output.append(last); } System.out.println(output.toString()); 
  • 使用StringBuilder (你做到了)
  • 定义两个变量 – previousCharcounter
  • 循环从0到str.length() – 1
  • 每次获取str.charat(i)并将其与存储在previousChar变量中的内容进行比较
  • 如果前一个字符相同,则递增一个计数器
  • 如果前一个字符不相同,并且计数器为1,则递增计数器
  • 如果前一个字符不相同,且计数器> 1,则追加counter + currentChar ,重置计数器
  • 比较后,分配当前的char previousChar
  • 覆盖角落案例,如“第一个字符”

这样的事情。

您可以使用以下步骤执行此操作:

  • 创建一个HashMap
  • 对于每个字符,从hashmap获取值 – 如果值为null,则输入1 -else,将值替换为(value + 1)
  • 迭代HashMap并保持连接(Value + Key)

在count = …行中,lastIndexOf不关心连续值,只会给出最后一次出现。

例如,在字符串“ABBA”中,子字符串将是整个字符串。

另外,取子串的长度相当于减去两个索引。

我真的认为你需要一个循环。 这是一个例子:

 public static String compress(String text) { String result = ""; int index = 0; while (index < text.length()) { char c = text.charAt(index); int count = count(text, index); if (count == 1) result += "" + c; else result += "" + count + c; index += count; } return result; } public static int count(String text, int index) { char c = text.charAt(index); int i = 1; while (index + i < text.length() && text.charAt(index + i) == c) i++; return i; } public static void main(String[] args) { String test = "AAABBCCC"; System.out.println(compress(test)); } 

请试试这个。 这可能有助于打印我们通过控制台传递字符串格式的字符数。

 import java.util.*; public class CountCharacterArray { private static Scanner inp; public static void main(String args[]) { inp = new Scanner(System.in); String str=inp.nextLine(); List arrlist = new ArrayList(); for(int i=0; i 

Java不是我的主要语言,几乎没有使用它,但我想试一试:]甚至不确定你的作业是否需要循环,但这是一个正则表达式方法:

  public static String compress_string(String inp) { String compressed = ""; Pattern pattern = Pattern.compile("([\\w])\\1*"); Matcher matcher = pattern.matcher(inp); while(matcher.find()) { String group = matcher.group(); if (group.length() > 1) compressed += group.length() + ""; compressed += group.charAt(0); } return compressed; } 

这只是另一种方式。

 public static String compressor(String raw) { StringBuilder builder = new StringBuilder(); int counter = 0; int length = raw.length(); int j = 0; while (counter < length) { j = 0; while (counter + j < length && raw.charAt(counter + j) == raw.charAt(counter)) { j++; } if (j > 1) { builder.append(j); } builder.append(raw.charAt(counter)); counter += j; } return builder.toString(); } 

如果您正在寻找基本解决方案,可以使用以下内容。 使用一个元素遍历字符串,并在找到所有元素出现后,删除该字符。 这样它就不会干扰下一次搜索。

 public static void main(String[] args) { String string = "aaabbbbbaccc"; int counter; String result=""; int i=0; while (i
		      	
 private String Comprimir(String input){ String output=""; Map map=new HashMap(); for(int i=0;i entry : map.entrySet()) { output+=entry.getValue()+""+entry.getKey().charValue(); } return output; } 

使用番石榴Multiset的另一种简单方法 –

 import java.util.Arrays; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import com.google.common.collect.Multiset.Entry; public class WordSpit { public static void main(String[] args) { String output=""; Multiset wordsMultiset = HashMultiset.create(); String[] words="AAABBBBCC".split(""); wordsMultiset.addAll(Arrays.asList(words)); for (Entry string : wordsMultiset.entrySet()) { if(!string.getElement().isEmpty()) output+=string.getCount()+""+string.getElement(); } System.out.println(output); } } 

考虑下面的解决方案,其中String s1标识给定String中可用的唯一字符(对于循环1),在第二个for循环中构建包含唯一字符的字符串s2,并且不会通过比较字符串重复它s1与s。

 public static void main(String[] args) { // TODO Auto-generated method stub String s = "aaaabbccccdddeee";//given string String s1 = ""; // string to identify how many unique letters are available in a string String s2=""; //decompressed string will be appended to this string int count=0; for(int i=0;i 

它可能会帮助你。

 public class StringCompresser { public static void main(String[] args) { System.out.println(compress("AAABBBBCC")); System.out.println(compress("AAABC")); System.out.println(compress("A")); System.out.println(compress("ABBDCC")); System.out.println(compress("AZXYC")); } static String compress(String str) { StringBuilder stringBuilder = new StringBuilder(); char[] charArray = str.toCharArray(); int count = 1; char lastChar = 0; char nextChar = 0; lastChar = charArray[0]; for (int i = 1; i < charArray.length; i++) { nextChar = charArray[i]; if (lastChar == nextChar) { count++; } else { stringBuilder.append(count).append(lastChar); count = 1; lastChar = nextChar; } } stringBuilder.append(count).append(lastChar); String compressed = stringBuilder.toString(); return compressed; } } 

输出:

 3A4B2C 3A1B1C 1A 1A2B1D2C 1A1Z1X1Y1C 

最简单的方法: – 时间复杂度 – O(n)

 public static void main(String[] args) { String str = "AAABBBBCC"; //input String int length = str.length(); //length of a String //Created an object of a StringBuilder class StringBuilder sb = new StringBuilder(); int count=1; //counter for counting number of occurances for(int i=0; i 

下面的代码将要求用户输入特定字符来计算事件。

 import java.util.Scanner; class CountingOccurences { public static void main(String[] args) { Scanner inp = new Scanner(System.in); String str; char ch; int count=0; System.out.println("Enter the string:"); str=inp.nextLine(); System.out.println("Enter th Char to see the occurence\n"); ch=inp.next().charAt(0); for(int i=0;i 
 public static char[] compressionTester( char[] s){ if(s == null){ throw new IllegalArgumentException(); } HashMap map = new HashMap<>(); for (int i = 0 ; i < s.length ; i++) { if(!map.containsKey(s[i])){ map.put(s[i], 1); } else{ int value = map.get(s[i]); value++; map.put(s[i],value); } } String newer=""; for( Character n : map.keySet()){ newer = newer + n + map.get(n); } char[] n = newer.toCharArray(); if(s.length > n.length){ return n; } else{ return s; } } 
 package com.tell.datetime; import java.util.Stack; public class StringCompression { public static void main(String[] args) { String input = "abbcccdddd"; System.out.println(compressString(input)); } public static String compressString(String input) { if (input == null || input.length() == 0) return input; String finalCompressedString = ""; String lastElement=""; char[] charArray = input.toCharArray(); Stack stack = new Stack(); int elementCount = 0; for (int i = 0; i < charArray.length; i++) { char currentElement = charArray[i]; if (i == 0) { stack.push((currentElement+"")); continue; } else { if ((currentElement+"").equalsIgnoreCase((String)stack.peek())) { stack.push(currentElement + ""); if(i==charArray.length-1) { while (!stack.isEmpty()) { lastElement = (String)stack.pop(); elementCount++; } finalCompressedString += lastElement + "" + elementCount; }else continue; } else { while (!stack.isEmpty()) { lastElement = (String)stack.pop(); elementCount++; } finalCompressedString += lastElement + "" + elementCount; elementCount=0; stack.push(currentElement+""); } } } if (finalCompressedString.length() >= input.length()) return input; else return finalCompressedString; } } 
 public class StringCompression { public static void main(String[] args){ String s = "aabcccccaaazdaaa"; char check = s.charAt(0); int count = 0; for(int i=0; i 

使用Map的答案对于像aabbbccddabc这样的情况aabbbccddabc因为在这种情况下输出应该是a2b3c2d2a1b1c1

在这种情况下,可以使用此实现:

 private String compressString(String input) { String output = ""; char[] arr = input.toCharArray(); Map myMap = new LinkedHashMap<>(); for (int i = 0; i < arr.length; i++) { if (i > 0 && arr[i] != arr[i - 1]) { output = output + arr[i - 1] + myMap.get(arr[i - 1]); myMap.put(arr[i - 1], 0); } if (myMap.containsKey(arr[i])) { myMap.put(arr[i], myMap.get(arr[i]) + 1); } else { myMap.put(arr[i], 1); } } for (Character c : myMap.keySet()) { if (myMap.get(c) != 0) { output = output + c + myMap.get(c); } } return output; }