我想反转 Java 中的字符串并删除和复制

I want to Reverse a string in Java and drop and duplicates

将字符串转换为字节:getBytes() 方法用于将输入字符串转换为字节[]。 方法:

  1. 创建一个长度相等的临时字节[] 到输入字符串的长度。
  2. 存储字节(我们使用 getBytes() 方法)以相反的顺序进入 临时字节[] .
  3. 使用 byte[] 创建一个新的 String abject 存储结果。

来源

// Java program to ReverseString using ByteArray. 
import java.lang.*; 
import java.io.*; 
import java.util.*; 

// Class of ReverseString 
class ReverseString 
{ 
    public static void main(String[] args) 
    { 
        String input = "Geeks"; 

        // getBytes() method to convert string  
        // into bytes[]. 
        byte [] strAsByteArray = input.getBytes(); 

        byte [] result =  
                   new byte [strAsByteArray.length]; 

        // Store result in reverse order into the 
        // result byte[] 
        for (int i = 0; i<strAsByteArray.length; i++) 
            result[i] =  
             strAsByteArray[strAsByteArray.length-i-1]; 

        System.out.println(new String(result)); 
    } 
} 

我希望输出为:skeg

您需要跟踪当前字节,如果与前一个字节相同,则不添加以下字节:

String input = "Geeks";
byte[] strAsByteArray = input.getBytes(); 
List<Byte> list = new ArrayList<>();
//byte[] result = new byte[strAsByteArray.length];
byte prev = 0;

for (int i=0; i < strAsByteArray.length; i++) {
    byte curr = strAsByteArray[strAsByteArray.length-i-1];
    if (curr != prev) {
        prev = curr;
        list.add(curr);
    }
}

byte[] result = new byte[list.size()];
for (int i=0; i < list.size(); ++i) {
    result[i] = list.get(i);
}

System.out.println(new String(result));

这会打印:

skeG

请注意,我最初使用列表来存储字节,因为在反向解析整个字符串之前,我们实际上并不知道固定字节数组的最终大小。我想找到一种使用流将 List<Byte> 转换为原始字节数组的巧妙方法。那失败了,我只是使用了增强的 for 循环。

您只需使用以下语法将 byte[] 转换为字符串:

System.out.println(new String(result, "UTF-8");

做嵌套循环。 这没有使用 collection/list。 在创建结果后放置它。

byte[] finalResult = new byte[result.length];
int k = 0;

for (int i = 0; i < result.length; i++) {
    boolean hasDuplicates = false;

    for (int j = i + 1; j < result.length; j++) {
        if (result[i] == result[j]) {
            hasDuplicates = true;
        }
    }

    if (!hasDuplicates) {
           finalResult[k++] = result[i];
    }
}

System.out.println(new String(finalResult));

示例:欢迎

结果:moclew

不确定这是否是您想要的回应。


有一种使用更少循环的更好方法。

这就是我一直在寻找的解决方案

    public class CodeExercise

{

public static void main(String[] args)
{
    String input = "abbac";

    char[] strArr= input.toCharArray();

  String result = "";

  // Reverse
  for(int i = strArr.length -1; i>=0; i--){
      result = result + strArr[i];

  }
  result = removeDuplicate(result.toCharArray());
  System.out.println(new String(result));
}

 // Collapsing any adjacent duplicate characters
public static String removeDuplicate(char[] chars)
{
    char prev = '[=11=]';
    int x = 0;

    for (int i = 0; i < chars.length; i++)
    {
        if (prev != chars[i]) {
            chars[x++] = chars[i];
            prev = chars[i];
        }
    }

    return new String(chars).substring(0, x);
}

}