This program is about String Compression in java
Java always evaluates left-to-right. So this:
s.charAt(i)!=s.charAt(i+1) || i+1>=s.length()
Evaluates s.charAt(i+1)
before it has checked i+1>=s.length()
. When i+1 >= s.length()
, s.charAt(i+1)
will fail, because it is beyond the end of the string.
Reverse the order of the operands:
i+1>=s.length() || s.charAt(i)!=s.charAt(i+1)
Because ||
is a short-circuiting operator, this only evaluates s.charAt(i)!=s.charAt(i+1)
if i+1>=s.length()
is false, so it doesn't fail with an exception in that case.
String compression algorithm in Java
You don't need two for loops for this and can do it in one go like so
String str = "aaabbbbccccca";
char[] chars = str.toCharArray();
char currentChar = str.length() > 0 ? chars[0] : ' ';
char prevChar = ' ';
int count = 1;
StringBuilder finalString = new StringBuilder();
if(str.length() > 0)
for(int i = 1; i < chars.length; i++)
{
if(currentChar == chars[i])
{
count++;
}else{
finalString.append(currentChar + "" + count);
prevChar = currentChar;
currentChar = chars[i];
count = 1;
}
}
if(str.length() > 0 && prevChar != currentChar)
finalString.append(currentChar + "" + count);
System.out.println(finalString.toString());
Output is: a3b4c5a1 for aaabbbbccccca
Compressing a string in Java
I would start at zero, and look forward:
public static void main(String[] args){
System.out.println("Enter a string: ");
String str = IO.readString();
int count = 0;
String result = "";
for (int i=0; i < str.length(); i++) {
char a = str.charAt(i);
count = 1;
while (i + 1 < str.length() && str.charAt(i) == str.charAt(i+1)) {
count++;
i++;
}
if (count == 1) {
result = result.concat(Character.toString(a));
} else {
result = result.concat(Integer.toString(count).concat(Character.toString(a)));
}
}
IO.outputStringAnswer(result);
}
Some outputs:
qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT => q9w5e2rt5y4qw2Er3T
qqwwwwwwwweeeeerrtyyyyyqqqqwEErTTT => 2q8w5e2rt5y4qw2Er3T
qqwwwwwwwweeeeerrtyyyyyqqqqwEErTXZ => 2q8w5e2rt5y4qw2ErTXZ
aaa => 3a
abc => abc
a => a
Java - Compressed String
public static String compressedString(String message) {
StringBuilder compressedString = new StringBuilder();
int total = 1;
for (int i = 0; i < message.length() - 1; i++){
if (message.charAt(i) == message.charAt(i+1)){
total++;
}
else if(total==1){
compressedString.append(message.charAt(i));
}
else
{
compressedString.append(message.charAt(i)).append(total);
total = 1;
}
}
if(message.charAt(message.length()-2) != message.charAt(message.length()-1)
compressedString.append(message.charAt(message.length()-1));
else
compressedString.append(message.charAt(message.length()-1)).append(total);
return compressedString.toString();
}
Related Topics
Map Json String Column of a JPA Entity to Java Object Automatically
How to Use Different Jsonproperty on Serialize & Deserialize Using Jackson API
How to Retrieve Mapping Table Name for an Entity in JPA At Runtime
How to Get Amount of Tens in a Int
Cannot Load Driver Class: Com.Mysql.Jdbc.Driver Spring Boot
Refreshing Existing Windows in Java Swing
Enable Jackson Deserialization of Empty Objects to Null
Gson Expected Begin_Array But Was String At Line 1 Column 62
Sharing a Variable Between Multiple Different Threads
How to Center Crop a Background Image of Linear Layout
Java.Sql.Sqlexception: Field Doesn't Have a Default Value
Android Room Persistent: Appdatabase_Impl Does Not Exist
How to Efficiently Read Multiple Json Files into a Dataframe or Javardd
Java.Time.Format.Datetimeparseexception: Text Could Not Be Parsed At Index 3
How to Handle Errors in Spring-Webflux
How to Run Single Cucumber Feature Files Through Command Prompt and Through Jenkins Using Maven