Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java压缩字符串_Java_String_Loops_Compression - Fatal编程技术网

Java压缩字符串

Java压缩字符串,java,string,loops,compression,Java,String,Loops,Compression,我需要创建一个接收字符串并返回字符串的方法 Ex输入:aaabbbcc Ex输出:3A4 B2C 嗯,这很尴尬,在今天的面试中我没能做到(我申请了一个初级职位),现在,在家里尝试我做了一些静态工作,我的意思是,不使用循环,这是一种无用的,但我不知道我是否没有得到足够的睡眠时间或其他东西,但我不能想出我的for循环应该是什么样子。代码如下: public static String Comprimir(String texto){ StringBuilder objString = ne

我需要创建一个接收字符串并返回字符串的方法

Ex输入:aaabbbcc

Ex输出:3A4 B2C

嗯,这很尴尬,在今天的面试中我没能做到(我申请了一个初级职位),现在,在家里尝试我做了一些静态工作,我的意思是,不使用循环,这是一种无用的,但我不知道我是否没有得到足够的睡眠时间或其他东西,但我不能想出我的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();
}
谢谢你的帮助,我正在努力提高我的逻辑能力。

  • 使用
    StringBuilder
    (您这样做了)
  • 定义两个变量-
    previousChar
    counter
  • 从0循环到
    str.length()
    -1
  • 每次获取
    str.charat(i)
    并将其与
    previousChar
    变量中存储的内容进行比较
  • 如果前一个字符相同,则递增一个计数器
  • 如果前一个字符不相同,且计数器为1,则递增计数器
  • 如果前一个字符不相同,且计数器大于1,则追加
    计数器+currentChar
    ,重置计数器
  • 比较后,分配当前字符
    previousChar
  • 像“first char”一样覆盖角落案例

类似的东西。

在字符串中循环,记住上次看到的内容。每次你看到相同的字母计数。当你看到一个新的字母时,把你数过的数字放到输出中,并将新的字母设置为你最后看到的字母

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());
String input=“aaabbbcc”;
整数计数=1;
char last=input.charAt(0);
StringBuilder输出=新的StringBuilder();
对于(int i=1;i1){
output.append(“+count+last”);
}否则{
输出。追加(最后);
}
计数=1;
最后=输入字符(i);
}
}
如果(计数>1){
output.append(“+count+last”);
}否则{
输出。追加(最后);
}
System.out.println(output.toString());

您可以使用以下步骤完成此操作:

  • 创建哈希映射
  • 对于每个字符,从hashmap中获取值 -如果该值为null,请输入1 -否则,将该值替换为(值+1)
  • 迭代HashMap并保持连接(值+键)

在计数=。。。行,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));
}
公共静态字符串压缩(字符串文本){
字符串结果=”;
int指数=0;
while(索引
专用字符串压缩程序(字符串输入){
字符串输出=”;
Map Map=newhashmap();

对于(inti=0;i,这只是另一种方法

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();
    }
公共静态字符串压缩器(字符串原始){
StringBuilder=新的StringBuilder();
int计数器=0;
int length=raw.length();
int j=0;
while(计数器<长度){
j=0;
而(计数器+j<长度和原始字符(计数器+j)=原始字符(计数器)){
j++;
}
如果(j>1){
附加(j);
}
builder.append(原始字符(计数器));
计数器+=j;
}
返回builder.toString();
}

Java不是我的主要语言,几乎从未使用过,但我想尝试一下:] 甚至不确定分配是否需要循环,但这里有一种regexp方法:

 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;
   }

下面的代码将要求用户输入一个特定字符来计算发生次数

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<str.length();i++)
    {
                if(str.charAt(i)==ch)
        {
            count++;
                }
    }

        System.out.println("The Character is Occuring");
        System.out.println(count+"Times");


}

}
import java.util.Scanner;
类计数发生率{
公共静态void main(字符串[]args){
扫描仪inp=新扫描仪(System.in);
字符串str;
char ch;
整数计数=0;
System.out.println(“输入字符串:”);
str=inp.nextLine();
System.out.println(“输入th Char以查看发生情况\n”);
ch=inp.next().charAt(0);
对于(int i=0;i
publicstaticchar[]compressionTester(char[]s){
如果(s==null){
抛出新的IllegalArgumentException();
}
HashMap=newHashMap();
对于(int i=0;in.长度){
返回n;
}
否则{
返回s;
}                       
}
package com.tell.datetime;
导入java.util.Stack;
公共类字符串压缩{
公共静态void main(字符串[]args){
字符串输入=“abbccdddd”;
System.out.println(压缩字符串(输入));
}
公共静态字符串压缩字符串(字符串输入){
if(input==null | | input.length()==0)
返回输入;
字符串finalCompressedString=“”;
字符串lastElement=“”;
煤焦[
 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;
   }
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<str.length();i++)
    {
                if(str.charAt(i)==ch)
        {
            count++;
                }
    }

        System.out.println("The Character is Occuring");
        System.out.println(count+"Times");


}

}
public static char[] compressionTester( char[] s){

    if(s == null){
        throw new IllegalArgumentException();
    }

    HashMap<Character, Integer> 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;
    }

}
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<Character> arrlist = new ArrayList<Character>();
   for(int i=0; i<str.length();i++){
       arrlist.add(str.charAt(i));
   }
   for(int i=0; i<str.length();i++){
       int freq = Collections.frequency(arrlist, str.charAt(i));
       System.out.println("Frequency of "+ str.charAt(i)+ "  is:   "+freq); 
   }
     }    
}
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<s.length();i++) {
        if(s1.indexOf(s.charAt(i))<0) {
            s1 = s1+s.charAt(i);
        }
    }
    for(int i=0;i<s1.length();i++) {
        for(int j=0;j<s.length();j++) {
            if(s1.charAt(i)==s.charAt(j)) {
                count++;
            }
        }
        s2=s2+s1.charAt(i)+count;
        count=0;
    }

    System.out.println(s2);
}
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
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<length; i++){
        //if i reaches at the end then append all and break the loop
        if(i==length-1){         
            sb.append(str.charAt(i)+""+count);
            break;
        }

        //if two successive chars are equal then increase the counter
        if(str.charAt(i)==str.charAt(i+1)){   
            count++;
        }
        else{
        //else append character with its count                            
            sb.append(str.charAt(i)+""+count);
            count=1;     //reseting the counter to 1
        }
   }

    //String representation of a StringBuilder object
    System.out.println(sb.toString());   

}
public static void main(String[] args) {
    String string = "aaabbbbbaccc";
    int counter;
    String result="";
    int i=0;
    while (i<string.length()){
        counter=1;
        for (int j=i+1;j<string.length();j++){ 
            System.out.println("string length ="+string.length());  
            if (string.charAt(i) == string.charAt(j)){
                  counter++;
            }
      }
      result = result+string.charAt(i)+counter; 
      string = string.replaceAll(String.valueOf(string.charAt(i)), ""); 
    }
    System.out.println("result is = "+result);
}
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<s.length(); i++){
            if(s.charAt(i) == check) {
                count++;
                if(i==s.length()-1){
                System.out.print(s.charAt(i));
                System.out.print(count);
             }
            } else {
                System.out.print(s.charAt(i-1));
                System.out.print(count);
                check = s.charAt(i);
                count = 1;
                if(i==s.length()-1){
                    System.out.print(s.charAt(i));
                    System.out.print(count);
                 }
            }
        }
    }
private String compressString(String input) {
        String output = "";
        char[] arr = input.toCharArray();
        Map<Character, Integer> 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;
    }
private static String compress(String s){
    StringBuilder result = new StringBuilder();
    int j = 0;
    s = s + '#';
    for(int i=1; i < s.length(); i++){
        if(s.charAt(i) != s.charAt(j)){
            result.append(i-j);
            result.append(s.charAt(j));
            j = i;
        }
    }
   return result.toString();
}
 // O(N) loop through entire character array
 // match current char with next one, if they matches count++
 // if don't then just append current char and counter value and then reset counter.
// special case is the last characters, for that just check if count value is > 0, if it's then append the counter value and the last char

 private String compress(String str) {
        char[] c = str.toCharArray();
        String newStr = "";
        int count = 1;
        for (int i = 0; i < c.length - 1; i++) {
            int j = i + 1;
            if (c[i] == c[j]) {
                count++;
            } else {
                newStr = newStr + c[i] + count;
                count = 1;
            }
        }

        // this is for the last strings...
        if (count > 0) {
            newStr = newStr + c[c.length - 1] + count;
        }

        return newStr;
    }
public class StringCompression {
    public static void main(String... args){
        String s="aabbcccaa";
        //a2b2c3a2

        for(int i=0;i<s.length()-1;i++){
            int count=1;
            while(i<s.length()-1 && s.charAt(i)==s.charAt(i+1)){
                count++;
                i++;
            }
            System.out.print(s.charAt(i));
            System.out.print(count);
        }
        System.out.println(" ");
    }
}