How to replace the "-" with the guessed letters? - java

I am trying to make a hangman game with String methods, however, I am having trouble replacing the "-" with the correct letter guessed, the specifications on my problem says that I need to concatenate the dashes with the letters that were guessed correctly.
this is the code I have so far for the method that checks if the letter is in the word
public static String reveal(String word, String guess)
{
String dashprints = "-", wholeword=" ";
for (int index=0; index<= word.length();index++)
{
if(index==word.indexOf(letters))
{
return dashprints;
}
else
{
dashprints=letters;
}
wholeword= dashprints+ wholeword;
}
return wholeword;
The word in the game is:
graphics
and the initial output is this:
"---------"
and the wanted output is:
"g-------"
however, the output I am getting right now is just this:
"-"

Hope this will work for you.
public static String reveal(String word, String guess) {
char[] guessChars = guess.toCharArray();
ArrayList<Character> missedChars = new ArrayList<Character>();
char[] out = new char[word.length()];
for (int i = 0; i < out.length; i++) {
out[i] = '_';
}
if (word.length() == guess.length()) {
for (int index = 0; index < word.length(); index++) {
int sts = word.indexOf(guessChars[index]);
if (sts != -1)
out[sts] = guessChars[index];
else
missedChars.add(guessChars[index]);
}
}
System.out.println("Missed Character: " + missedChars.toString());
return new String(out);
}
You can change out[i] = '_'; to out[i] = '-';

Related

How to replace characters in a string in Java without using .replace?

The goal of this program is to prompt the user for a single character and a phrase, and then replace any instances of that character within that phrase with a '$'. My program below does just that, but when I showed it to my professor I was told that I cannot use .replace in the methods I built, so I have to figure out a way to not use that. I have worked at it for a while, and thus far I know that I can replace it with a for loop, but after several frustrating iterations, I can't seem to get it right. Excuse me if my code looks funky, I am still an introductory java student so I'm still learning the basics. I have provided a proposed solution at the end of my code snippet below.
public static char getKeyCharacter(String userInput) {
char keyCharacter;
Scanner inputStream = new Scanner(System.in);
while(userInput.length() > 1)
{
System.out.println("Please enter a SINGLE character to use as key: ");
userInput = inputStream.nextLine();
}
keyCharacter = userInput.charAt(0);
return keyCharacter;
}
public static String getString(String userResponse) {
Scanner inputStream = new Scanner(System.in);
String theString;
while(userResponse.length() > 500) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
while(userResponse.length() < 4) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
theString = userResponse;
return theString;
}
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
maskedString = maskedString + theString.replace(keyCharacter, mask);
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
public static String removeCharacter(String theString, char keyCharacter) {
String modifiedString = " ";
final char replaceChar = ' ';
modifiedString = modifiedString + theString.replace(keyCharacter, replaceChar);
System.out.println("String with " + keyCharacter + " removed:");
return modifiedString;
}
public static int countKey(String theString, char keyCharacter) {
int charCount = 0;
for (int c = 0; c < theString.length(); c++) {
if (theString.charAt(c) == keyCharacter) {
charCount++;
}
}
System.out.println("Occurences of " + keyCharacter + " in string:");
return charCount;
}
}
I believe the solution is will look something like this, but thus far I've been unsuccesful -
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
for (int k = 0; k < theString.length(); k++) {
if (theString.charAt(k) == keyCharacter) {
keyCharacter = mask;
}
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
My issue lies in making the maskedString = theString with all the keyCharacters replaced by mask. For the record, I have yet to learn anything about those fancy arrays, so if there is a way to do this using a simple for loop I would greatly appreciate it. Thank you for the assistance in advance!
I would use a StringBuilder and String#toCharArray() with a simple for-each loop. Like,
public static String maskCharacter(String theString, char keyCharacter){
StringBuilder sb = new StringBuilder();
for (char ch : theString.toCharArray()) {
if (ch == keyCharacter) {
sb.append('$'); // <-- mask keyCharacter(s).
} else {
sb.append(ch); // <-- it isn't the character to mask
}
}
return sb.toString();
}
I wouldn't use a StringBuilder: just use the result of toCharArray() directly:
char[] cs = theString.toCharArray();
for (int i = 0; i < cs.length; ++i) {
if (cs[i] == keyCharacter) cs[i] = '$';
}
return new String(cs);
Not only is it more concise, but:
It will run faster, because it's cheaper to access an array element than to invoke a method; and because it doesn't require StringBuilder's internal buffer to resize (although you could just pre-size that);
It will use less memory, because it doesn't require storage for the copy inside StringBuilder.
public static String maskCharacter(String theString, char keyCharacter){
String masked = "";
for (int i = 0 ; i < theString.length() ; i++) {
if (theString.charAt(i) == keyCharacter) {
masked += "$";
}
else {
masked+=theString.charAt(i)+"";
}
}
return masked;
}
An answer that only uses string concatenation and basic character access.
You seem to know that you can concatenate something to a string and get a different string.
maskedString = maskedString + ...;
You also know you can build a for-loop that gets each individual character using .charAt()
for (int k = 0; k < theString.length(); k++) {
char nch = theString.charAt(k);
}
You can check equality between chars
if (nch == keyCharacter)
... assuming you know about else-branches, isn't it clear you just need to put them together?
if (nch == keyCharacter) {
// append '$' to maskedString
}
else {
// append nch to maskedString
}
Of course this creates a new string on every loop iteration so it is not terribly efficient. But I don't think that's the point of the exercise.

Put even characters in uppercase, but skipping spaces

I'm trying to convert some text so that every even character becomes uppercase. This works, but if there's a space between words, the code takes the space as a character too. So for example, if the input text is "this is a test", the output is "tHiS Is a tEsT". I want it to ignore the spaces and give "tHiS iS a TeSt" as output.
I now have the following code:
private String result;
private String letter;
private void generateText() {
result = "";
String input = editTextInput.getText().toString();
String lowerCase = input.toLowerCase();
char[] charArray = lowerCase.toCharArray();
for(int i=0;i<charArray.length;i++){
if(String.valueOf(charArray[i]).equals(" ")){
//I don't know what to put here
letter = String.valueOf(charArray[i]);
}else{
if(i%2 == 0){
letter = String.valueOf(charArray[i]);
}else if(i%2 == 1){
letter = String.valueOf(charArray[i]).toUpperCase();
}
}
result += letter ;
}
Log.d("result", result);
}
What do I have to do to skip the spaces?
If it's possible, I would like to skip punctuation marks too, or in general, every character which is not a letter.
Thanks in advance!
(For those who are wondering, I'm making a Spongebob meme text generator app)
If you want to do alternate logic in a loop, you could normally use i % 2 == 0, or (i & 1) == 1, but since the alternation is conditional, you need a variable to store the "state". With simple alternation, a boolean variable is the obvious choice.
Also, continuously converting each char to a String is bad for performance. Just update the char[].
private static String upperEven(String input) {
char[] buf = input.toLowerCase().toCharArray();
boolean upper = false;
for (int i = 0; i < buf.length; i++) {
if (Character.isLetter(buf[i])) {
if (upper)
buf[i] = Character.toUpperCase(buf[i]);
upper = ! upper;
}
}
return new String(buf);
}
Test
System.out.println(upperEven("this IS a TEST"));
Output
tHiS iS a TeSt
Code can be compressed/obscured to this: ;-)
private static String upperEven(String s) {
char[] c = s.toCharArray();
boolean t = false;
for (int i = 0; i < c.length; i++)
if (Character.isLetter(c[i]))
c[i] = ((t = ! t) ? Character.toLowerCase(c[i]) : Character.toUpperCase(c[i]));
return new String(c);
}
This is my solution.
private static void generateText() {
String result = "";
String input = "i am a engineer and student of nit.";
String lowerCase = input.toLowerCase();
Boolean isLower = false;
char[] charArray = lowerCase.toCharArray();
for (int i = 0; i < lowerCase.length(); i++) {
String letter = String.valueOf(charArray[i]);
if (!Character.isLetter(charArray[i])) {
result += letter;
} else {
if(isLower)
letter = letter.toUpperCase();
result += letter;
isLower = !isLower;
}
}
System.out.println(result);
}

How to remove repeated letter from words in Java

i have problem writing java code to remove repeated letters from word.This code will remove repeated letter by accepting only one of the letter which is repeating . Suppose, if input is "SUSHIL" then output would be "SUHIL".
This java code i write.
import java.io.*;
import java.util.*;
public class Repeat
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
char ch1, ch2;
int i, j;
int l = name.length();
String result = "";
for (i = 0; i < l; i++)
{
for (j = 1; j < l; j++)
{
ch1 = name.charAt(i);
ch2 = name.charAt(j);
if (ch1 != ch2)
{
result = result + ch1;
break;
}
}
}
System.out.println("Output:" + result);
}
}
try this:
private static String removeRepeat(String input){
Set<Character> str = new LinkedHashSet<Character>();
for(int n=0;n<input.length();n++){
str.add(input.charAt(n));
}
return str.toString();
}
good point from the comment, changed to LinkedHashSet.
It may be the crap code, but what I mean is don't reinvent the wheel, only if you have to
char ch1,ch2;
int l=name.length();
String result="";
for(int i=0;i<l;i++){
if(name.indexOf(name.charAt(i))==i){
result+=name.charAt(i);
}
}
System.out.println(result);
input = SUSHSILHI
output = SUHIL
You should do the opposite: add the first letter to result, then check if the next letter is already in result:
boolean exist=false;
result=name.charAt(0);
for (i=1; i<l;i++) {
exist=false;
int j=0;
while (exist=false && j<i) {
if(name.charAt(i)==charAt(j)) {
exist=true;
}
j++;
}
if(exist==false){
result=result+name.charAt(i);
}
}
The for checks for all the string name, then the while checks for the characters already in result, if it doesn't already exist, else it doesn't do anything.
Using indexOf() , one for loop should work, like below
String name="SUSHIL";
String newName="";
int i=0;
int l=name.length();
for(i=0;i<l;i++)
{
char ch1=name.charAt(i);
if(!(newName.indexOf(ch1)>-1))
{
newName=newName + ch1;
}
}
System.out.println("Output:"+newName);
String name = "SUSHIL";
char ch1 = 0, ch2;
int i, j;
int l = name.length();
StringBuilder sb = new StringBuilder();
for (i = 0; i < l; i++)
{
//this is used to append char to StringBuilder
boolean shouldAppend = true;
//if we don't check if the length is equal to 0 to start then the below loop will never run and the result would be an empty string so just append the first character to the StringBuilder
if (sb.length() == 0)
{
sb.append(name.charAt(i));
shouldAppend = false;
}
else
{
for (j = 0; j < sb.length(); j++)
{
ch1 = name.charAt(i);
ch2 = sb.charAt(j);
if (ch1 == ch2)
{
//StringBuilder contains ch1 so turn shouldAppend to false and break out of this inner loop
shouldAppend = false;
break;
}
}
}
if (shouldAppend) sb.append(ch1);
}
System.out.println("Output:" + sb.toString());
Try:
//Globally
List<Character> list = new ArrayList<Character>();
public String remRepeats(String original)
{
char ch = original.charAt(0);
if (original.length() == 1)
return original;
if (list.contains(ch))
return remRepeats(original.substring(1));
else
{
list.add(ch);
return ch + remRepeats(original.substring(1));
}
}
List<Character> characters = new ArrayList<>();
char[] chars = name.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for(char currChar:chars) {
if (!characters.contains(currChar)) {
characters.add(currChar);
stringBuilder.append(currChar);
}
}
System.out.println(stringBuilder);

Replace method without using .replace()

Ok, so I am required to create a program that will replace a word in a string according to a string, and also given a replacement. (In this case replace UK with United Kingdom)
Below is my code, but it doesn't work
import java.util.*;
public class replace
{
public static void main(String[]args){
replace("The UK should not be written as uk", "UK", "United Kingdom");
}
static void replace(String input, String seed, String replacement){
String s = "";
ArrayList<String> bla = new ArrayList<String>();
for(int i = 0; i < input.length();i++){
if(input.charAt(i) != ' '){
s = s + input.charAt(i);
}
if(input.charAt(i) == ' ' || i+1 == input.length()){
bla.add(s);
s = "";
}
}
String out = "";
for(int i = 0; i < bla.size(); i++){
if(bla.get(i) == seed){
bla.set(i, replacement);
}
}
for(int i = 0; i < bla.size(); i++){
out = out + bla.get(i)+ " ";
}
System.out.println(out);
}
}
For some reason it's not replacing my variable with the replacement
String out = "";
for(int i = 0; i < bla.size(); i++){
if(bla.get(i) == seed){
bla.set(i, replacement);
}
}
Any ideas why this might be?
Thanks in advance
Replace:
if(bla.get(i) == seed)
With:
if(bla.get(i).equals(seed))
The first compares reference, the second equality.
You should also use a StringBuilder to concatanate Strings, and keep it inside the loop:
ArrayList<String> bla = new ArrayList<String>();
for(int i = 0; i < input.length(); i++) {
StringBuilder s = new StringBuilder();
if(input.charAt(i) != ' ')
s.append(input.charAt(i));
if(input.charAt(i) == ' ' || i+1 == input.length())
bla.add(s.toString());
}
Using a StringBuilder is more efficient.

Java compressing Strings

I need to create a method that receives a String and also returns a String.
Ex input: AAABBBBCC
Ex output: 3A4B2C
Well, this is quite embarrassing and I couldn't manage to do it on the interview that I had today ( I was applying for a Junior position ), now, trying at home I made something that works statically, I mean, not using a loop which is kind of useless but I don't know if I'm not getting enough hours of sleep or something but I can't figure it out how my for loop should look like. This is the code:
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();
}
Thanks for your help, I'm trying to improve my logic skills.
Loop through the string remembering what you last saw. Every time you see the same letter count. When you see a new letter put what you have counted onto the output and set the new letter as what you have last seen.
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());
You can do that using the following steps:
Create a HashMap
For every character, Get the value from the hashmap
-If the value is null, enter 1
-else, replace the value with (value+1)
Iterate over the HashMap and keep concatenating (Value+Key)
use StringBuilder (you did that)
define two variables - previousChar and counter
loop from 0 to str.length() - 1
each time get str.charat(i) and compare it to what's stored in the previousChar variable
if the previous char is the same, increment a counter
if the previous char is not the same, and counter is 1, increment counter
if the previous char is not the same, and counter is >1, append counter + currentChar, reset counter
after the comparison, assign the current char previousChar
cover corner cases like "first char"
Something like that.
The easiest approach:- Time Complexity - 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<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());
}
In the count=... line, lastIndexOf will not care about consecutive values, and will just give the last occurence.
For instance, in the string "ABBA", the substring would be the whole string.
Also, taking the length of the substring is equivalent to subtracting the two indexes.
I really think that you need a loop.
Here is an example :
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));
}
Please try this one. This may help to print the count of characters which we pass on string format through console.
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);
}
}
}
Java's not my main language, hardly ever use it, but I wanted to give it a shot :]
Not even sure if your assignment requires a loop, but here's a regexp approach:
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;
}
This is just one more way of doing it.
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();
}
The following can be used if you are looking for a basic solution. Iterate through the string with one element and after finding all the element occurrences, remove that character. So that it will not interfere in the next search.
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);
}
And the output will be :=
result is = a4b5c3
private String Comprimir(String input){
String output="";
Map<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<input.length();i++){
Character character=input.charAt(i);
if(map.containsKey(character)){
map.put(character, map.get(character)+1);
}else
map.put(character, 1);
}
for (Entry<Character, Integer> entry : map.entrySet()) {
output+=entry.getValue()+""+entry.getKey().charValue();
}
return output;
}
One other simple way using Multiset of guava-
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<String> wordsMultiset = HashMultiset.create();
String[] words="AAABBBBCC".split("");
wordsMultiset.addAll(Arrays.asList(words));
for (Entry<String> string : wordsMultiset.entrySet()) {
if(!string.getElement().isEmpty())
output+=string.getCount()+""+string.getElement();
}
System.out.println(output);
}
}
consider the below Solution in which the String s1 identifies the unique characters that are available in a given String s (for loop 1), in the second for loop build a string s2 that contains unique character and no of times it is repeated by comparing string s1 with 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<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);
}
It may help you.
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;
}
}
Output:
3A4B2C
3A1B1C
1A
1A2B1D2C
1A1Z1X1Y1C
The answers which used Map will not work for cases like aabbbccddabc as in that case the output should be a2b3c2d2a1b1c1.
In that case this implementation can be used :
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;
}
O(n) approach
No need for hashing. The idea is to find the first Non-matching character.
The count of each character would be the difference in the indices of both characters.
for a detailed answer: https://stackoverflow.com/a/55898810/7972621
The only catch is that we need to add a dummy letter so that the comparison for
the last character is possible.
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();
}
The code below will ask the user for user to input a specific character to count the occurrence .
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;
}
}
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);
}
}
}
}
// 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(" ");
}
}
This is a leet code problem 443. Most of the answers here uses StringBuilder or a HashMap, the actual problem statement is to solve using the input char array and in place array modification.
public int compress(char[] chars) {
int startIndex = 0;
int lastArrayIndex = 0;
if (chars.length == 1) {
return 1;
}
if (chars.length == 0) {
return 0;
}
for (int j = startIndex + 1; j < chars.length; j++) {
if (chars[startIndex] != chars[j]) {
chars[lastArrayIndex] = chars[startIndex];
lastArrayIndex++;
if ((j - startIndex) > 1) {
for (char c : String.valueOf(j - startIndex).toCharArray()) {
chars[lastArrayIndex] = c;
lastArrayIndex++;
}
}
startIndex = j;
}
if (j == chars.length - 1) {
if (j - startIndex >= 1) {
j = chars.length;
chars[lastArrayIndex] = chars[startIndex];
lastArrayIndex++;
for (char c : String.valueOf(j - startIndex).toCharArray()) {
chars[lastArrayIndex] = c;
lastArrayIndex++;
}
} else {
chars[lastArrayIndex] = chars[startIndex];
lastArrayIndex++;
}
}
}
return lastArrayIndex;
}
}

Categories

Resources