Character count in Java - java

consider this code:
package q2b;
public class Q2b {
public static void main(String[] args) {
String kalimat = new String("Sue sells sea shells on the seashore!");
String upperLetter = "";
String removeLetter = "";
//Code to count the spacing in the string
for (int i = 0; i < kalimat.length(); i++) {
if (kalimat.charAt(i) == 's') {
upperLetter += 'S';
} else {
upperLetter += kalimat.charAt(i);
}
}
System.out.println("The letter modification in the string are :" + upperLetter);
}
}
My Question:
what code should I type to get how many lowercase letter 's' has been replace?

Add this:
int count = 0; // <-- here
for (int i = 0; i < kalimat.length(); i++) {
if (kalimat.charAt(i) == 's') {
upperLetter += 'S';
count++; // <-- and here
} else {
upperLetter += kalimat.charAt(i);
}
}
In the end you will have the number of substitutions in the variable count.

Declare and initialize an int variable to 0 outside the processing loop. Increment it while processing whenever you replace a s with an S.
As a side note, it is obviously out of the scope of this question, but using the + operator for repetitive String concatenation is highly inefficient. You should use a StringBuilder instead.

Based on my understanding about your question, the below code may help you,
Declared a variable 'count' and it will increase in the presence of each lowercase letter 's' in the iteration.
public class Q2b {
public static void main(String[] args) {
String kalimat = new String("Sue sells sea shells on the seashore!");
String upperLetter = "";
String removeLetter = "";
int count=0;
//Code to count the spacing in the string
for (int i = 0; i < kalimat.length(); i++) {
if (kalimat.charAt(i) == 's') {
upperLetter += 'S';
count++;
} else {
upperLetter += kalimat.charAt(i);
}
}
System.out.println("The letter modification in the string are :" + upperLetter);
System.out.println("Number of lower case letter 's' is :" + count);
}
}

Related

How can I trim the last letter of a String while looping (until what's left is a single letter)?

I'm creating a program that will count the number of letters, vowels and consonants from what user put into using Scanner.
Here's my code:
'''
static String phrase;
static int vowel = 0;
static int consonant = 0;
static String reverse = "";
public static void countChar() {
System.out.println("\nNumber of characters: " + phrase.length());
}
public static void countVowelCons() {
phrase = phrase.toLowerCase();
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == 'a' || phrase.charAt(i) == 'e' || phrase.charAt(i) == 'i' || phrase.charAt(i) == 'o'
|| phrase.charAt(i) == 'u') {
vowel++;
} else if (phrase.charAt(i) >= 'a' && phrase.charAt(i) <= 'z') {
consonant++;
}
}
System.out.println("Number of vowels: " + vowel);
System.out.println("Number of consonants: " + consonant);
}
public static void reverseString() {
for (int i = phrase.length() - 1; i >= 0; i--) {
reverse += phrase.charAt(i);
}
System.out.println(reverse);
}
'''
In the reverseString() method, how can I make the reversed String get trimmed or make the last letter deleted in a loop until all what's left is a single letter.
For example:
User inputs "qwertyuiop".
What should be the output is something like this:
poiuytrewq poiuytrew poiuytre poiuytr poiuyt poiuy poiu poi po p
How can I make it done like that? Please help thanks alot!
'''
public static void reverseString() {
for (int i = phrase.length() - 1; i >= 0; i--) {
reverse += phrase.charAt(i);
}
System.out.println(reverse);
'''
public static void reverseString() {
StringBuilder reverseStr = new StringBuilder();
for (int i = phrase.length() - 1; i >= 0; i--) {
reverseStr.append(phrase.charAt(i));
}
reverse = reverseStr.toString();
System.out.println(reverse);
}
// OR You can use inbuild method reverse() of StringBuilder
public static void reverseString() {
StringBuilder reverseStr = new StringBuilder(phrase);
reverse = reverseStr.reverse().toString();
System.out.println(reverse);
}
Sometimes rather than fixing code, you find an easier way:
vowel = phrase.replaceAll("(?i)[^aeiou]", "").length();
consonant = phrase.replaceAll("(?i)[^b-z&&[^eiou]]", "").length();
reverse = new StringBuilder(phrase).reverse().toString();
See live demo.
The character counts work by replacing with blank (ie "deleting") characters that aren't the type being counted and using the length of the resulting string.
Reversing uses functionality provided by the StringBuilder built-in class.

String index out of range in jva

A string is a palindrome if it is spelled the same way backward and
forward.
Examples of palindromes include “Radar” and “Dammit, I’m mad!”.
Write a java program, PalindromeTester, that asks the user to enter a
word or sentence and then checks whether the entered string is a
palindrome or not.
Spaces, nonalphabetics (.,!:?-()\";), and case within the string have
to be ignored e.g., "Drab as a fool, aloof as a bard." is a
palindrome.
Your implementation should define and use the method isPalindrome to
test if a certain string is a palindrome. The signature of the
isPalindrome method is as follows:
boolean isPalindrome(String)
Following is a sample run of the program. The user’s input is shown in bold.
java PalindromeTester
Introduction to Computer Programming (CMPS 200)
Spring 2015-16 2 of 3
Enter a string: I love CMPS 200
The string "I love CMPS 200" is NOT a palindrome.
This is the code I made, it keeps giving me an error.
I would like to know what my error is and whether there's a faster easier way of writing this code
import java.util.Scanner;
public class PalindromeTester {
public static void main (String args []) {
Scanner console = new Scanner(System.in);
System.out.println("Enter a string: ");
String palindrome = console.next();
if (isPalindrome (palindrome)) {
System.out.print("The string \""+palindrome+" is a palindrome.");
} else {
System.out.print("The string \""+palindrome+" is NOT a palindrome.");
}
}
public static boolean isPalindrome (String palindrome) {
int constant = 1;
for (int i = 0 ; i <= (palindrome.length()-1) ; i++) {
for (int z= (palindrome.length()-1);i >= 0; i--) {
if (palindrome.charAt(i) <'#'||'Z'<palindrome.charAt(i)&&palindrome.charAt(i)<'`'||'['<palindrome.charAt(i)&&palindrome.charAt(i)<'{') {
i=i+1;
}
if (palindrome.charAt(z)<'#'||'Z'<palindrome.charAt(z)&&palindrome.charAt(z)<'`'||'['<palindrome.charAt(z)&&palindrome.charAt(z)<'{') {
z=z+1;
}
if (palindrome.charAt(i)==(palindrome.charAt(z))) {
constant = constant * 1;
} else {
constant = constant * 0;
}
}
}
if (constant == 0 ) {
return false;
} else {
return true;
}
}
}
One approach would be to strip the non alpha characters out of the string. Then check if the string is the same as itself reversed (while upper case):
public static boolean isPalindrome(String palindrome) {
StringBuilder sanitisedString = new StringBuilder();
for(char c : palindrome.toCharArray()) {
if(Character.isLetter(c)) {
sanitisedString.append(c);
}
}
return sanitisedString.toString().toUpperCase().equals(sanitisedString.reverse().toString().toUpperCase());
}
Index out of range is caused by palindrome.charAt(z)) after z = z + 1;
Keep simple :
public static boolean isPalindrome(String palindrome)
{
palindrome = palindrome.replaceAll("\\W", ""); // remove all non word character
palindrome = palindrome.toLowerCase();
int size = palindrome.length();
int halfSize = size / 2;
for (int i = 0; i < halfSize; i++)
{
if(palindrome.charAt(i) != palindrome.charAt(size - i - 1))
return false;
}
return true;
}
Why not just make a new String and save the reversed source(String) in it.
public static boolean readstring(String s)
{
String b = "";
for (int i= s.length() -1; i >=0 ;i--)
{
b = b + s.charAt(i);
}
System.out.print(b +" and "+ s +" ");
return b == s || b.Equals(s);
}
EDIT: Hopefully this meets the requirements, by the way dont use the word "ignore" but "allow"
public boolean isPalindrome(String word) {
int backward = word.length() - 1;
for (int x = 0; x < word.length(); x++) {
if (word.charAt(x)!= word.charAt(backward--)) {
return false;
}
}
return true;
}

Counting words in a string using methods

I have a project to make a program that takes a string as input and then prints the number of words in the string as output. We are supposed to use 3 methods in this, one to read input, one to print the output, and one to count the words.
I know I am missing something basic but I have spent hours on this and cannot figure out why the program wont run as it should. I need to keep the program pretty simple so I dont want to edit it too much, just find the issue and fix it so it will run correctly.
Example: Enter a string of text: The quick brown fox jumped over the lazy dog. 9 words
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter text: ");
String words = wordInput(in);
int count = wordCount(words);
System.out.println(words);
System.out.println(count);
printLine(count);
}
private static String wordInput(Scanner in)
{
String words = in.nextLine();
return words;
}
private static int wordCount(String words)
{
int length = words.length();
int ctr = 0;
int spot = 0;
int stop = 1;
char space = ' ';
char end = '.';
char com = ',';
char yes = '!';
char question = '?';
while (length > 0 && stop > 0)
{
if (words.charAt(spot) == space)
{
ctr++;
spot++;
}
else if (words.charAt(spot) == com)
{
spot++;
}
else if (words.charAt(spot) == yes || words.charAt(spot) == end || words.charAt(spot) == question)
{
stop = -1;
}
else if (spot > length)
{
stop = -1;
}
else
spot++;
}
return ctr + 1;
}
private static void printLine(int ctr)
{
System.out.println(ctr + " words");
}
Here is a rewritten wordCount that does as you request, minimal changes to the code. However, I am not sure it produces the answers you expect.
private static int wordCount(String words)
{
int length = words.length();
int ctr = 0;
int spot = 0;
char space = ' ';
char end = '.';
char com = ',';
char yes = '!';
char question = '?';
while (spot < length)
{
if (words.charAt(spot) == space)
{
ctr++;
spot++;
}
else if (words.charAt(spot) == com)
{
spot++;
}
else if (words.charAt(spot) == yes || words.charAt(spot) == end || words.charAt(spot) == question)
{
break;
}
else
spot++;
}
return ctr + 1;
}
However, fundamentally you are trying to count words in a string, and that is a known art. A few options and further reading:
http://www.quickprogrammingtips.com/java/find-number-of-words-in-a-string-in-java.html
Count words in a string method?
Which leads to a simpler result of:
private static int wordCount(String words) {
return words.split("\\s+").length;
}
Going on the assumption that whoever enters the string is not going to make a grammar error, try split the string at all spaces and set it equal to a string[]. Here is an example:
String temp = JOptionPane.showInputDialog(null, "Enter some text here");
String[] words = temp.split(" ");
JOptionPane.showMessage(null, String.format("Words used %d", words.length));

Java Case Converter, most of the program is done, having trouble with case options?

My program worked fine before I tried implementing the conversion options. All I am trying to do is implement a U/u or L/l input option for either convert the string to Uppercase or Lowercase. Help please?
import java.util.Scanner;
public class CaseManipulation {
public static void main(String[] args) {
boolean up, low;
char up[] = {'U', 'u'};
char low[] = {'L', 'l'};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an input String: ");
String inputString = scanner.nextLine();
System.out.print("Case Conversion Option(U/u for uppercase, L/l for lowercase):");
char caseoption = scanner.nextLine();
if (caseoption == up[]) {
System.out.println("Upper Case: " + toUpperCase(inputString));
} else if (caseoption == low[]) {
System.out.println("Lower Case: " + toLowerCase(inputString));
}
//is_uppercase();
//System.out.println("Upper Case: " + toUpperCase(inputString));
//System.out.println("Lower Case: " + toLowerCase(inputString));
}
//public static boolean is_uppercase(char caseoption) {
// if (char caseoption == ) {
// }
//}
public static String toUpperCase(String inputString) {
String result = "";
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
char currentCharToUpperCase = Character.toUpperCase(currentChar);
result = result + currentCharToUpperCase;
}
return result;
}
public static String toLowerCase(String inputString) {
String result = "";
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
char currentCharToLowerCase = Character.toLowerCase(currentChar);
result = result + currentCharToLowerCase;
}
return result;
}
}
Basically, your if condition is comparing the object/memory references of the two objects, not their values...
if (caseoption == up[]) {...
caseoption is never likely to be equal to up...
Instead, you should be comparing their contents...
if (caseoption == up[0] || caseoption == up[1]) {...
A simpler solution might be to convert the caseoption into a single use case, for example...
if (Character.toUpperCase(caseoption) == 'U') {...

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