Reverse a String without affecting special characters - java

Why is it throwing an error? Any help would be appreciated
public class RAWS
{
public String rawsc(String ori)
{
String temp="";
for(int i=0;i<ori.length();i++)
{
char c=ori.charAt(i);
if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
temp=c+temp;
}
for(int i=0;i<ori.length();i++)
{
char c=ori.charAt(i);
if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
ori.replace(c, temp.charAt(i));
}
for(int i=0;i<ori.length();i++)
{
System.out.println(ori.charAt(i));
}
return(ori);
}
public static void main(String[] args)
{
String str="a,b$c";
RAWS ob=new RAWS();
String new1=ob.rawsc(str);
for(int i=0;i<new1.length();i++)
{
System.out.print(new1.charAt(i)+" ");
}
}
}
Editor:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at arraygs.RAWS.rawsc(RAWS.java:22)
at arraygs.RAWS.main(RAWS.java:30)

The problematic part is the call temp.charAt(i) in
for(int i=0;i<ori.length();i++){
char c=ori.charAt(i);
if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
ori.replace(c, temp.charAt(i));
}
The string temp may not have the length of ori. The reason for this is the if-condition in the first loop
for(int i=0;i<ori.length();i++) {
char c=ori.charAt(i);
if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
temp=c+temp;
}
So accessing the position i in temp (as part of the second loop) may result in the java.lang.StringIndexOutOfBoundsException.

public class PracticeJava{
public static void main(String []args){
String str = "\"Str!ng\"";
System.out.println("Actual str: "+str);
System.out.println("Reverse str: "+reverseStrSpecial(str));
}
public static String reverseStrSpecial(String str) {
int len = str.length();
char[] revStrArr = new char[len];
int j = len-1;
for (int i=0; i <= j; ) {
if(!Character.isAlphabetic(str.charAt(i))) {
revStrArr[i] = str.charAt(i);
i++;
} else if (!Character.isAlphabetic(str.charAt(j))) {
revStrArr[j] = str.charAt(j);
j--;
} else {
revStrArr[j] = str.charAt(i);
revStrArr[i] = str.charAt(j);
j--;
i++;
}
}
return new String(revStrArr);
}
}

public class Solution {
public static void main(String[] args) {
System.out.println(reverseString("a,b$c"));
}
/**
* Reverse string with maintaining special character in place
*
* Algorithm:
* 1. create temporary array
* 2. copy all character from original array excluding special character
* 3. reverse the temporary array
* 4. start copying temporary array into original if element is an alphabetic character
* #param input
* #return
*/
public static String reverseString(String input) {
char[] inputArr = input.toCharArray();
char[] tempArr = new char[input.length()];
int i=0;
int j=0;
for (char ch:inputArr){
if(Character.isAlphabetic(ch)){
tempArr[i] = ch;
i++;
}
}
i--;
while(j<i){
char temp = tempArr[i];
tempArr[i]= tempArr[j];
tempArr[j]=temp;
j++;
i--;
}
for(i=0,j=0;i<input.length();i++){
if(Character.isAlphabetic(inputArr[i])){
inputArr[i]= tempArr[j++];
}
}
return new String(inputArr);
}
}

public class Ex {
public static void main(String[] args) {
String ss= "Hello###+dnksjaf#+43####";
char[] c=new char[ss.length()];
String spclCharLessString="";
String spclCharLessStringrev="";
for(int i=0;i<ss.length();i++) {
if(((ss.charAt(i)>='A'&&ss.charAt(i)<='Z')|(ss.charAt(i)>='a'&&ss.charAt(i)<='z')|(ss.charAt(i)>='0'&&ss.charAt(i)<='9'))) {
spclCharLessString+=ss.charAt(i);
}
c[i]=ss.charAt(i);
}
for(int i=spclCharLessString.length()-1;i>=0;i--) {
spclCharLessStringrev+=spclCharLessString.charAt(i);
}
int spclCharSpace=0;
for(int i=0;i<ss.length();i++) {
if(((ss.charAt(i)>='A'&&ss.charAt(i)<='Z')|(ss.charAt(i)>='a'&&ss.charAt(i)<='z')|(ss.charAt(i)>='0'&&ss.charAt(i)<='9'))) {
c[i]=spclCharLessStringrev.charAt(i-spclCharSpace);
}else {
spclCharSpace++;
}
}
System.out.println(spclCharLessStringrev);
for(char c1:c) {
System.out.print(c1);
}
}
}

using regex seems to be a good idea.here is my javascript solution.
var reverseOnlyLetters = function(S) {
let arr = S.split('')
let regex = /^[a-zA-Z]{1}$/
let i=0,j=arr.length-1;
while(i<j){
if(regex.test(arr[i]) && regex.test(arr[j])){
let temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
i++;j--
}else{
if(!regex.test(arr[i])) i++
if(!regex.test(arr[j])) j--
}
}
return arr.join('')
};

str=input("enter any string")
l=[]
s=""
list=list(str)
for i in str:
k=ord(i)
if((k>=48 and k<=57) or (k>=65 and k<=90) or(k>=97 and k<=122)):
l.append(i)
l.reverse()
print(s.join(l))
by sreevidhya bontha

public static void main(String[] args) {
String str = "fed#cb%a!";
char arr[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) < 48 || (str.charAt(i) > 57 && str.charAt(i) < 65) || (str.charAt(i) > 90 && str.charAt(i) < 97) || str.charAt(i) > 122)
arr[i] = str.charAt(i);
else
arr[i] = '0';
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
stack.push(str.charAt(i));
}
int i=0;
while(!stack.isEmpty()){
char pop = stack.pop();
if (!(pop < 48 || (pop > 57 && pop < 65) || (pop > 90 && pop < 97) || pop > 122)){
arr[i] = pop;
++i;
}
if(arr[i]!='0'){
++i;
}
}
for ( i = 0; i < str.length(); i++) {
System.out.print(arr[i]);
}
}
Time complexity: O(n)

public static void main(String[] args) {
String a = "ab$cd";
char[] b = a.toCharArray();
int c = b.length;
for (int i = 0; i < c / 2; i++) {
if (Character.isAlphabetic(b[i]) || Character.isDigit(b[i])) {
char temp = b[i];
b[i] = b[c - i - 1];
b[c - i - 1] = temp;
}
}
System.out.println(String.valueOf(b));
}

public class MuthuTest {
static Map list = new HashMap();
/*
* public static int fact(int n) { if(n>1) return n*fact(n-1); else return 1; }
*/
#SuppressWarnings("deprecation")
public static void main(String[] args) {
String j = "muthu is a good boy.";
int v = 0;
String[] s = j.split(" ");
for (int h = 0; h < s.length; h++) {
String y;
y = s[h].replaceAll("[A-Za-z0-9]", "");
list.put(h, y);
}
// MuthuTest.li(s);
for (int u = s.length - 1; u >= 0; u--) {
if (u == 0) {
s[u] = s[u].replaceAll("[^A-Za-z0-9]", "");
System.out.print(s[u] + list.get(v));
} else {
s[u] = s[u].replaceAll("[^A-Za-z0-9]", "");
System.out.print(s[u] + list.get(v) + " ");
}
v++;
}
}
}

[Java] Simple way to reverse only alphabets without affecting special chars.
public class StringReverse {
public static void main(String[] args) {
reverseString("T#E$J#A%S");
}
//S#A$JE#T
private static void reverseString(String s){
int len = s.length();
char[] arr = new char[len];
for(int i=0; i<len; i++){
char ch = s.charAt(i);
if(Character.isAlphabetic(ch)){
arr[len-1-i] = ch;
}else{
arr[i] = ch;
}
}
System.out.println(new String(arr));
}
}

import java.util.HashMap;
import java.util.Map.Entry;
public class ReverseString {
public static void main(String[] args) {
HashMap<Character, Integer> map = new HashMap<>();
String s = "S#3jakd*nd%4*ksdkj12";
String str = "";
int len = s.length();
for (int i = len - 1; i >= 0; i--) {
char ch = s.charAt(i);
if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
str = str + s.charAt(i);
} else {
map.put(s.charAt(i), new Integer(s.indexOf(s.charAt(i))));
}
}
for (Entry<Character, Integer> entry : map.entrySet()) {
str = str.substring(0, entry.getValue()) + entry.getKey() + str.substring(entry.getValue(), str.length());
}
System.out.println(str);
}
}

Reverse a String without affecting any special chars. Note that it is just for a String but not combination of Strings that would eventually be an array of Strings.
Code :
public class Info {
// Input : str = "Ab,c,de!$" o/p : ed,c,bA!$
public static void main(String[] args) {
String input = "Ab,c,de!$";
char[] inputCharArray = input.toCharArray();
reverseIgnoreSpecialCharacters(inputCharArray);
}
public static void reverseIgnoreSpecialCharacters(char[] charArray) {
int j = charArray.length-1;
int k = 0;
for(int i = charArray.length-1; i>=0; i--) {
if(!(charArray[i] >= 65 && charArray[i] <=90) || !(charArray[i] >= 97 && charArray[i] <=122)) {
charArray[j] = charArray[i];
System.out.print(charArray[j]);
j--;
}
else {
charArray[k] = charArray[i];
System.out.print(charArray[k]);
k++;
}
}
}
}
for multiple Strings, you could something like below :
Code :
public class Info {
// Input : str = "Ab,c,de!$" o/p : ed,c,bA!$
public static void main(String[] args) {
String input = "Ab,c,de!$ Abhi$hek";
String[] inputStringArray = input.split("\\ ");
for(int i = inputStringArray.length-1; i>=0; i--) {
char[] strArray = inputStringArray[i].toCharArray();
reverseIgnoreSpecialCharacters(strArray);
System.out.print(" ");
}
}
public static void reverseIgnoreSpecialCharacters(char[] charArray) {
int j = charArray.length-1;
int k = 0;
for(int i = charArray.length-1; i>=0; i--) {
if(!(charArray[i] >= 65 && charArray[i] <=90) || !(charArray[i] >= 97 && charArray[i] <=122)) {
charArray[j] = charArray[i];
System.out.print(charArray[j]);
j--;
}
else {
charArray[k] = charArray[i];
System.out.print(charArray[k]);
k++;
}
}
}
}

Simplest Way to Do it..
String name = "Ma#hb$oobSi#ddi$qui";
char oldchararr[] = name.toCharArray();
String newStr = new StringBuffer(name.replaceAll("[^A-Za-z0-9]", "")).reverse().toString();
char newchar[] = newStr.toCharArray();
int j = 0;
for (int i = 0; i < oldchararr.length; i++) {
if (Character.isAlphabetic(oldchararr[i]) || Character.isDigit(oldchararr[i])) {
oldchararr[i] = newchar[j];
j++;
}
}
for (char c : oldchararr) {
System.out.print(c);
}

Related

Reverse encoded string

i am asking for help on how i would go about reversing my code so that the input 'A2B5C2' will give me the output 'AABBBBBCC', any suggestions?
Thanks
public static void printRLE(String str) {
int n = str.length();
for (int i = 0; i < n; i++) {
// Count occurrences of current character
int count = 1;
while (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
// Print character and its count
System.out.print(str.charAt(i));
System.out.print(count);
}
}
public static void main(String[] args) {
String str = "AABBBBBCC";
printRLE(str);
}
To get the case, the number will more than 9, I'd suggest a simple regex to match letter+number, then just repeat the letter the number of times you need :
static String getRevRLE(String str) {
StringBuilder res = new StringBuilder();
Matcher m = Pattern.compile("([a-zA-Z][0-9]+)").matcher(str);
while (m.find()) {
String g = m.group();
res.append(g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))));
}
return res.toString();
}
Using the Streams API you can reduce to
static String getRevRLE(String str) {
return Pattern.compile("([a-zA-Z][0-9]+)").matcher(str).results()
.map(MatchResult::group)
.map(g -> g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))))
.collect(Collectors.joining());
}
Testing
public static void main(String[] args) {
String str = "AABBBBBCCCCCCCCCCCCCCCCCCCC";
String rle = getRLE(str);
String res = getRevRLE(rle);
System.out.println(res + " " + res.equals(str)); // AABBBBBCCCCCCCCCCCCCCCCCCCC true
}
Here you go:
public static String encode(String input) {
String output = "";
while (true) {
char c = input.charAt(0);
String countStr = "";
char current;
for (int i = 1; i < input.length() && Character.isDigit(current = input.charAt(i)); i++)
countStr += current;
int count = Integer.parseInt(countStr);
for (int i = 0; i < count; i++)
output += c;
int trimLength = 1 + countStr.length();
if (trimLength >= input.length())
return output;
else
input = input.substring(trimLength);
}
}
You can do this task like this:
public static String printRLE(String str) {
int n = str.length();
String result = "";
for (int i = 0; i < n - 1; i++) {
char ch = str.charAt(i);
if (!Character.isDigit(ch)) {
if (Character.isDigit(str.charAt(i + 1))) {
int fi = i + 1;
i += 2;
while (i < n && Character.isDigit(str.charAt(i))) i++;
int repeat = Integer.parseInt(str.substring(fi, i));
result += String.valueOf(ch).repeat(repeat);
i--;
} else result += ch;
}
}
return result;
}
public static void main(String[] args) {
String str = "10A10B32C1";
System.out.println(printRLE(str));
}
, output
AAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBC

How can I compare these two strings and remove a common letter without using arrays?

This was the code I designed to solve this problem but it seems not to work at all.I used nested for loops to compare the letters of the first string and the second string since they are likely to have different lengths
import java.util.*;
public class Trim
{
public static String myTrim(String input, String list)
{
String r = "";
for (int i = 1; i < input.length();i++)
{
for (int k = 1; k < list.length();k++)
{
if (input.charAt(i) != list.charAt(i))
{
r += input.charAt(i);
}
}
}
return r;
}
}
I guess you should use the method String.indexOf.
So:
public static String myTrim(String input, String list)
{
StringBuilder result = new StringBuilder();
char c;
for (int i = 0; i < input.length(); i++)
{
c = input.charAt(i);
if (list.indexOf(c) < 0)
result.append(c);
}
return result.toString();
}
Try using a flag to determine whether to character gets repeated or not:
String r = "";
for (int i = input.length() - 1; 0 <= i; i --) {
if (-1 == list.indexOf(input.charAt(i))) {
r += input.charAt(i);
}
}
OR
String r = "";
boolean found;
for (int i = input.length() - 1, j = list.length() - 1; 0 <= i; i--) {
found = false;
for (int k = j; 0 <= k; k--) {
if (list.charAt(k) == input.charAt(i)) {
found = true;
break;
}
}
if (!found) {
r += input.charAt(i);
}
}
We have to filter out the characters from input which appears in list.
Now we have to check whether each character of the input appears in the list or not.
The k value will be less then list.length() if the character of input present in the list string.
After the loop we check the k value and append it to the new string.
public static String myTrim(String input, String list)
{
String r = "";
for (int i = 0; i < input.length();i++)
{
int k = 0;
for (; k < list.length();k++)
{
if (input.charAt(i) == list.charAt(k))
{
break;
}
}
if(k == list.length())
r += input.charAt(i);
}
return r;
}
A nice one-liner solution would be to use Guava Charmatcher:
CharMatcher.anyOf(list).removeFrom(input);
I have tried this code and it's working fine with both of your inputs
for (int i = 0; i < S1.length(); i++) {
for(int j=0;j< S2.length();j++) {
if(S1.charAt(i)==S2.charAt(j)) {
char Temp= S2.charAt(j);
String Temp2=String.valueOf(Temp);
S1=S1.replace(Temp2, "");
}
}
}
This is code
import java.util.Scanner;
public class StringRemoveChar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String S1, S2;
S1 = scanner.nextLine();
S2 = scanner.nextLine();
for (int i = 0; i < S1.length(); i++) {
for (int j = 0; j < S2.length(); j++) {
if (S1.charAt(i) == S2.charAt(j)) {
char Temp = S2.charAt(j);
String Temp2 = String.valueOf(Temp);
S1 = S1.replace(Temp2, "");
System.out.println(S1.length());
}
}
}
System.out.println(S1);
}
}
Input:
Miyazaki
you
Output:
Miazaki
We can use replaceAll and use one loop over ,this will make the solution simple
public static String myTrim(String input, String list)
{
for(int i=0;i<list.length();i++)
{
input=input.replaceAll(list.charAt(i)+"","");
}
return input;
}
Input: myTrim("Miyazaki","you")
Output: Miazaki
Full code for reference
package stackoverflow.string;
public class StringManipulation
{
public static void main(String[] args)
{
System.out.println(myTrim("University of Miami","city"));
}
public static String myTrim(String input, String list)
{
for(int i=0;i<list.length();i++)
{
input=input.replaceAll(list.charAt(i)+"","");
}
return input;
}
}

Logic Correction for reverse words input-[ Tom Cat ] O/p [Cat Tom] without using split function

public static void reverse() {
int x=0;
char temp = 0;
String toStrore;
char checkSpace=' ';
System.out.println("Enter a line to reverse");
Scanner sc=new Scanner(System.in);
String userInput=sc.nextLine();
char[] charArray=userInput.toCharArray();
for(int i=charArray.length-1;i>=0;i--){
char tchar=charArray[i];
while(tchar==checkSpace){
x = ++i;
for(int j=x;j<=charArray.length-1;i++){
temp=(char) (temp+charArray[j]);
System.out.print(temp);
}
}
}
}
Please help me with logic.
NOTE: I DONT WANT TO USE ANY INBUILT FUNCTION EXCEPT lenght().
Here something, but you have to at least use String.charAt() and String.length(). The string is reversed by searching backwards until you find a space. Then it appends what's after the space until it reaches the end of the string or finds another space. Lastly, the first word will get added to the result.
public class MyClass {
public static void main(String args[]) {
System.out.println(reverse("The quick brown fox jumps over the lazy dog"));
}
private static String reverse(String data) {
String result = "";
// Build the string in reverse as you find spaces
for (int i = data.length() - 1; i > -1; i--) {
if (data.charAt(i) == ' ') {
int j = i + 1;
while (j < data.length() && data.charAt(j) != ' ') {
result += data.charAt(j++);
}
result += " ";
}
}
// Add the first word to the result
int i = 0;
while (i < data.length() && data.charAt(i) != ' ') {
result += data.charAt(i++);
}
return result;
}
}
Result
dog lazy the over jumps fox brown quick The
try out this one
import java.util.Arrays;
public class Reverse {
public static void main(String... args) {
getReversed("Tom Cat");
}
public static void getReversed(String str) {
char[] arr = str.toCharArray();
int len = 0;
for (char ch : arr) {
if (ch == ' ') {
len++;
}
}
String[] res = new String[len + 1];
int start = 0;
int idx = len;
while (idx > -1) {
StringBuilder builder = new StringBuilder();
for (int i = start; i < arr.length; i++) {
if (arr[i] != ' ') {
builder.append(arr[i]);
if (i == arr.length - 1) {
res[idx--] = builder.toString();
}
} else {
res[idx--] = builder.toString();
builder.setLength(0);
start = i;
}
}
}
System.out.println(Arrays.toString(res));
}
}
Updated optimized code
public static void main(String... args) {
String str = "Cat Tom";
char[] charArr = str.toCharArray();
int len = charArr.length;
ArrayList<String> list = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
char ch = charArr[i];
if (ch == ' ') {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
} else if (i == len - 1) {
list.add(stringBuilder.append(ch).toString());
} else {
stringBuilder.append(ch);
}
}
Collections.reverse(list);
System.out.println(list);
}
Output
[Cat, Tom]

find all palindromes in string

I need to find all the palindromes in a string. It takes user input
example: "abbaalla"
it loops through creating a substring that changes as the loop progresses.
example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..
once it reaches the max length of the word it iterates the start of the substring and repeats
example: check palindrome "b" "bb" "bba" and so on..
I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"
the final output should be a string that includes all palindromes. in this case;
output: "abba alla"
Also this program currently results in: String index out of range: -1
public static String findAllPalindromes(String input){
int indexStart = 0;
int wordMax = input.length();
int wordLength;
String checkPalindrome;
String allPalindromes = "";
for (wordLength = 2; wordLength <= wordMax; wordLength++) {
//creates a substring to check against isAllPalindrome method
checkPalindrome = input.substring(indexStart, wordLength);
//checks checkPalindrome string to see if it is a palindrome
if (isAllPalindrome(checkPalindrome) == true){
allPalindromes += " " + checkPalindrome;
if (checkPalindrome.length() >= allPalindromes.length()){
allPalindromes = checkPalindrome;
}
}
//once program reads string through once, increment index and scan text again
if (wordLength == wordMax && indexStart < wordMax){
indexStart++;
wordLength = 0;
}
}
System.out.println("The palindromes in the text are: ");
System.out.println(allPalindromes);
return allPalindromes;
}
public static Set<CharSequence> printAllPalindromes(String input) {
if (input.length() <= 2) {
return Collections.emptySet();
}
Set<CharSequence> out = new HashSet<CharSequence>();
int length = input.length();
for (int i = 1; i <= length; i++) {
for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
if (input.charAt(j) == input.charAt(k)) {
out.add(input.subSequence(j, k + 1));
} else {
break;
}
}
}
return out;
}
Simple Brute force way-->
public class AllPalindromes {
public static boolean checkPalindrome(String str) {
for(int i=0;i<=str.length()/2;i++)
if(str.charAt(i)!=str.charAt(str.length()-1-i))
return false;
return true;
}
public static void printAllPalindrome(String str) {
for(int i=0;i<=str.length();i++)
for(int j=i;j<str.length();j++)
if(checkPalindrome(str.substring(i,j+1)))
System.out.println(str.substring(i,j+1));
}
public static void main(String[] args) {
printAllPalindrome("abbaalla");
}
}
Here is the solution which displays all palindromes. (Only those palindromes which are of length greater than 3. You can change the if condition inside the loop if you want to print them all.)
Note that #jw23's solution does not display the palindromes which are of even length — only the odd length ones.
public class HelloWorld{
public static void printPalindromes(String s) {
if (s == null || s.length() < 3)
return;
System.out.println("Odd Length Palindromes:");
// Odd Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
System.out.println("\nEven Length Palindromes:");
// Even Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
}
public static void main(String[] args){
String s = "abcbaaabbaa";
printPalindromes(s);
}
}
public class Palindrome
{
static int count=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String array[]=s1.split("");
System.out.println("Palindromes are :");
for(int i=0;i<=array.length;i++)
{
for(int j=0;j<i;j++)
{
String B=s1.substring(j,i);
verify(B);
}
}
System.out.println("\n"+count);
sc.close();
}
public static void verify(String s1)
{
StringBuilder sb=new StringBuilder(s1);
String s2=sb.reverse().toString();
if(s1.equals(s2))
{
System.out.print(s1+" ");
count++;
}
}
}
My own logic for palindrome program for all substrings
public class Test1 {
public static void main(String[] args) {
String s = "bob";
ArrayList<Character> chr = new ArrayList<Character>();
ArrayList<String> subs= new ArrayList<String>();
for (int i=0;i<s.length();i++)
{
chr.add(s.charAt(i));
}
System.out.println(chr.toString());
StringBuilder subString = new StringBuilder();
for(int i=0; i < s.length();i++)
{
for(int j=i+1;j<s.length();j++)
{
for(int k=i;k<=j;k++)
{
subString.append(chr.get(k));
}
System.out.println(subString.toString());
subs.add(subString.toString());
subString.setLength(0);
}
}
System.out.println(subs);
for(String st : subs)
{
String st2 = new StringBuffer(st).reverse().toString();
if(st.equals(st2))
{
System.out.println(st+" is a palindrome");
}
else
{
System.out.println(st+" not a palindrome");
}
}
}
}
Print All Palindromes in the string
import java.util.*;
class AllPalindroms
{
public static void main(String args[])
{
String input = "abbaalla";
if (input.length() <= 1)
{
System.out.println("Not Palindrome Found.");
}
else
{
int length = input.length();
Set<String> set = new HashSet<String>();
for (int i = 0; i <length; i++)
{
//if(i==0)
for (int j=i+1;j<length+1;j++)
{
String s = input.substring(i, j);
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if(s.equals(sb.toString()) && s.length()>1)
{
set.add(s);
}
}
}
System.out.println(set);
}
}
}
My code to count all palindromes in a string:
import java.util.Scanner;
public class CountPalindromeSapient {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the given string: ");
String inputStr = sc.nextLine();
countPalindrome(inputStr);
System.out.println("\nTotal count of Palindromes are: "+count);
sc.close();
}
private static int countPalindrome(String inputStr) {
int count = 0;
int len = inputStr.length();
int startIndex =0;
String subString = "";
System.out.println( "Possible substrings are: ");
for (int i = 0; i < len; i++) {
for (int j = startIndex; j <= len; j++) {
subString = inputStr.substring(startIndex, j);
System.out.println(subString);
count = checkPalindrome(subString);
}
startIndex++;
}
return count;
}
private static int checkPalindrome(String subString) {
// TODO Auto-generated method stub
int subLen = subString.length();
boolean isPalindrome = false;
for(int k=0; k<subLen; k++,subLen-- ) { // Important
if (subString.charAt(k) != subString.charAt(subLen -1)) {
isPalindrome = false;
break;
}else {
isPalindrome = true;
}
}
if(isPalindrome == true) {
count ++;
}
return count;
}
}
class StringTest {
public static void main(String[] args) {
StringTest test = new StringTest();
boolean bool = test.checkPalindrom("abbaalla");
if(!bool)
System.out.println("String is not palindrom");
}
private boolean checkPalindrom(String k){
int[] count= new int[k.length()];
boolean[] arr = new boolean[k.length()];
for(int t=0;t<k.length();t++){
int j=0;
char ch = k.charAt(t);
for(int x=t+1;x<k.length();x++){
if(j<count.length){
if(ch == k.charAt(x))
count[j] = x + 1;
else
count[j] = 0;
j++;
}
}
arr[t] = workOnArr(count,t,k);
}
for(int z=0;z<arr.length;z++){
if(arr[z])
return true;
}
return false;
}
private boolean workOnArr(int[] s,int z,String w){
int j = s.length - 1;
while(j -- > 0){
if(s[j] != 0){
if(isPalindrom(w.substring(z, s[j]))){
if(w.substring(z, s[j]).length() > 1){
System.out.println(w.substring(z, s[j]).length());
System.out.println(w.substring(z, s[j]));
}
return true;
}
}
}
return false;
}
private boolean isPalindrom(String s){
int j= s.length() -1;
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(j))
return false;
j--;
}
return true;
}
}
output:-
given palindrom are:-
abba, bb, aa, alla, ll
Question: All the palindromes from a word.
public class Test4 {
public static void main(String[] args) {
String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
allpalindromicsubstrings(a);
}// main
private static void allpalindromicsubstrings(String a) {
Set<String> set = new HashSet<String>();
for (int i = 0; i < a.length(); i++) {
// odd length palindrome
expand(a, i, i, set);
// even length palindrome
expand(a, i, i + 1, set);
} // for
set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
}// ee
private static void expand(String a, int start, int last, Set<String> set) {
// run till a[start...last] is a palindrome
while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {
set.add(a.substring(start, last + 1));
// expand in both directions
start--;
last++;
}
}// ee
}
The output palindromes in the word =>
niin
ADA
eye
MADAM
iniini
GiniiniG
ii
MeyeM
ini
Print all the palindromes in a string:
public class test1 {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
System.out.println(list);
List<String> plist = new ArrayList<>();
for(int i = 0 ; i <list.size();i++) {
String curr =list.get(i);
if(ispalin(curr)) {plist.add(curr);}
}//for
System.out.println("palindrome list => " +plist);
}//main
private static boolean ispalin(String curr) {
if(curr == null || curr.length() == 0) {return false;}
return new StringBuffer(curr).reverse().toString().equals(curr);
}
}
The output is: palindrome list => [MADAM, GiniiniG]
Another Method in Java 8:
public class B {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
// list to stream
// for Multi Threaded environment
Stream<String> stream = list.parallelStream();
// also,Stream<String> stream = list.stream(); for single Threaded environment
long palindrome = stream.filter(B::isPalindrome)// find all palindromes
.peek(System.out::println) // write each match
.count();// terminal - return a count
System.out.println("Count of palindromes: " + palindrome);
// System.out.println("List => " + list);
}
private static boolean isPalindrome(String aa) {
return new StringBuffer(aa).reverse().toString().equals(aa);
}
}
Output:
GiniiniG
MADAM
Count of palindromes: 2
Java program to enter a string and frame a word by joining all the first character of each word.
Display a new word.
import java.util.*;
public class Anshu {
public static void main(String args[]) {
Scanner in = new Scanner(System.in)
System.out.println("Enter a string");
String s = in .nextLine();
char ch = s.charAt(0);
System.out.print(ch);
s = s.toUpperCase;
int l = s.length();
for (int i = 0; i < l; i++)
char a = s.charAt(i);
if (Character.isWhiteSpace())
System.out.print(s.charAt(i + 1) + "");
}
}

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