Skip to content

Instantly share code, notes, and snippets.

@bmakarand2009
Created August 10, 2020 21:25
Show Gist options
  • Save bmakarand2009/46d0f8290271c2948bef80159863a588 to your computer and use it in GitHub Desktop.
Save bmakarand2009/46d0f8290271c2948bef80159863a588 to your computer and use it in GitHub Desktop.
//Reverse an input string by maintaining the spaces in the same order as input string.
//For ex:
//Input String : Hello Welcome To DEV Test
//There are spaces at locations - 6 , 14, 17, 21
package com.company;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
public class ReverseString {
/*
* Complete the 'ReverseStringWithSpaces' function below.
*
* The function is expected to return a STRING.
*/
public static String ReverseStringWithSpaces(String input) {
StringBuilder sBldr = new StringBuilder();
//step1. find all the spaces in the string
String[] arr = input.split(" ");
int[] spaces = new int[arr.length];
for(int i=0; i< arr.length; i++){
spaces[i] = arr[i].length() +1;
}
System.out.println(Arrays.toString(spaces));
String reversed = reverseStringWithNoSpaces(input);
System.out.println(reversed);
// //step2. convert the string to char array
// //and then check length is reached and then create a stirng with space
int beginIndex = 0;
int endIndex = 0;
boolean ended = false;
for(int j=0; j<spaces.length; j++){
endIndex = beginIndex + spaces[j] -1;
if (endIndex >= reversed.length()){
endIndex = reversed.length();
ended = true;
}
sBldr.append(reversed.substring(beginIndex, endIndex));
sBldr.append(' ');
beginIndex = endIndex;
if(ended){
break;
}
}
return sBldr.toString();
}
public static String reverseStringWithNoSpaces(String input){
String noSpaceInput= input.replaceAll("\\s", "");
StringBuilder sb = new StringBuilder();
char[] inputArr = noSpaceInput.toCharArray();
for(int i=inputArr.length -1; i>=0; i--){
sb.append(inputArr[i]);
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment