Interview Question
Country: United States
class ReverseString {
public static void main(String[] args) {
String input = "1+2*3-20";
// getBytes() method to convert string
// into bytes[].
byte[] strAsByteArray = input.getBytes();
byte[] result = new byte[strAsByteArray.length];
// Store result in reverse order into the
// result byte[]
for (int i = 0; i < strAsByteArray.length; i++){
result[i] = strAsByteArray[strAsByteArray.length - i - 1];
}
byte temp = result[0];
result[0] = result[1];
result[1] = temp;
System.out.println(new String(result));
}
}
/*
Reverse this string 1+2*3-20. Note: 20 must be retained as is.
Expected output: 20-3*2+1
*/
public class ReverseEquation {
public static void main(String[] args) {
final String input = "1+2*3-20";
System.out.println(new ReverseEquation().reverse(input));
//prints 20-3*2+1
}
String reverse(String s) {
BreakIterator b = java.text.BreakIterator.getWordInstance();
b.setText(s);
StringBuilder sb = new StringBuilder();
for (int end = b.last(), start = b.previous(); start != BreakIterator.DONE;
end = start, start = b.previous()) {
String w = s.substring(start, end);
sb.append(w);
}
return sb.toString();
}
}
def reverseString(theString):
operatorList = ['*', '+', '-', '/']
finalString = ""
i = len(theString) - 1
while (i >= 0):
currentNum = ""
while (i >= 0 and theString[i] not in operatorList):
currentNum = theString[i] + currentNum
i -= 1
totalString += currentNum
if (i >= 0):
totalString += theString[i]
i -= 1
package string;
import java.util.Scanner;
public class ReverseExp {
public static String reverExp(String s)
{
char[] ch=s.toCharArray();
String res="";int k=0;
for (int i = ch.length-1 ; i >= 0; i--) {
int start=i;
while(i>=0 && ch[i] >=48 && ch[i] <= 57)
{
i--;
}
int end=i+1;
while(end <= start)
{
res=res+ch[end];
end++;
}
if(i>=0) {
res=res+ch[i];}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String: ");
String s=sc.nextLine();
s=reverExp(s);
System.out.println("Reverse of expression: "+s);
}
}
package string;
import java.util.Scanner;
public class ReverseExp {
public static String reverExp(String s)
{
char[] ch=s.toCharArray();
String res="";int k=0;
for (int i = ch.length-1 ; i >= 0; i--) {
int start=i;
while(i>=0 && ch[i] >=48 && ch[i] <= 57)
{
i--;
}
int end=i+1;
while(end <= start)
{
res=res+ch[end];
end++;
}
if(i>=0) {
res=res+ch[i];}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String: ");
String s=sc.nextLine();
s=reverExp(s);
System.out.println("Reverse of expression: "+s);
}
}
package string;
import java.util.Scanner;
public class ReverseExp {
public static String reverExp(String s)
{
char[] ch=s.toCharArray();
String res="";int k=0;
for (int i = ch.length-1 ; i >= 0; i--) {
int start=i;
while(i>=0 && ch[i] >=48 && ch[i] <= 57)
{
i--;
}
int end=i+1;
while(end <= start)
{
res=res+ch[end];
end++;
}
if(i>=0) {
res=res+ch[i];}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String: ");
String s=sc.nextLine();
s=reverExp(s);
System.out.println("Reverse of expression: "+s);
}
}
package string;
import java.util.Scanner;
public class ReverseExp {
public static String reverExp(String s)
{
char[] ch=s.toCharArray();
String res="";int k=0;
for (int i = ch.length-1 ; i >= 0; i--) {
int start=i;
while(i>=0 && ch[i] >=48 && ch[i] <= 57)
{
i--;
}
int end=i+1;
while(end <= start)
{
res=res+ch[end];
end++;
}
if(i>=0) {
res=res+ch[i];}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String: ");
String s=sc.nextLine();
s=reverExp(s);
System.out.println("Reverse of expression: "+s);
}
}
var string2 = "1+2*3-20";
var sliceout1= string2.slice(0,6);
var sliceout2= string2.slice(6);
var splitString1= sliceout1.split("");
splitString1.push(sliceout2);
var reverseArray= splitString1.reverse();
console.log(reverseArray);
reverseArray.toString();
console.log("The reversed string is: "+reverseArray);
var string2 = "1+2*3-20";
var sliceout1= string2.slice(0,6);
var sliceout2= string2.slice(6);
var splitString1= sliceout1.split("");
splitString1.push(sliceout2);
var reverseArray= splitString1.reverse();
console.log(reverseArray);
reverseArray.toString();
console.log("The reversed string is: "+reverseArray);
#generic solution
def reverseString(str1):
lst_str = []
str2 = ''
str3 = ''
str_flag = 0
sy_flag = 0
for i in str1:
if i.isdigit():
if sy_flag == 1:
lst_str.append(str2)
str2 = ''
sy_flag = 0
str2 = str2 + i
str_flag = 1
else:
if str_flag == 1:
lst_str.append(str2)
str2 = ''
str_flag = 0
str2 = i + str2
sy_flag = 1
lst_str.append(str2)
for j in reversed(lst_str):
str3 = str3 + j
return str3
str1 = '1+2*3-20'
print reverseString(str1)
#below one is more generic
str1 = '-41+2**36-20/+6*'
print reverseString(str1)
#generic solution
def reverseString(str1):
lst_str = []
str2 = ''
str3 = ''
str_flag = 0
sy_flag = 0
for i in str1:
if i.isdigit():
if sy_flag == 1:
lst_str.append(str2)
str2 = ''
sy_flag = 0
str2 = str2 + i
str_flag = 1
else:
if str_flag == 1:
lst_str.append(str2)
str2 = ''
str_flag = 0
str2 = i + str2
sy_flag = 1
lst_str.append(str2)
for j in reversed(lst_str):
str3 = str3 + j
return str3
str1 = '1+2*3-20'
print reverseString(str1)
#below one is more generic
str1 = '-41+2**36-20/+6*'
print reverseString(str1)
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
getline(cin,str);
string output="";
int j;
for(int i=str.length()-1;i>=-1;i--)
{
if(i==-1 || str[i] == '*' || str[i] == '+' || str[i] == '-' || str[i] == '/')
{
int j = i;
j++;
while(str[j] != '*' && str[j] != '-' && str[j] != '+' && str[j] != '/' && str.length() > j)
{
output = output + str[j];
j++;
}
if(i != -1)
output = output + str[i];
}
}
cout<<output<<endl;
return 0;}
Reverse the whole string as is. Next reverse the numbers.
Logic remains same as "This is a book" --> "book a is This" excepting , watch out for mathematical operations, as suppose to space.
C Solution:
#include <stdio.h>
#include <string.h>
void ReverseStringUtil(char *str,int start,int end)
{
char temp;
while(start < end)
{
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main()
{
char *str = (char *)malloc(100 * sizeof(char));
int start, end;
fgets(str,100,stdin);
str[strlen(str)-1] = '\0';
printf("Input string is - %s \n", str);
ReverseStringUtil(str,0,strlen(str)-1);
printf("Semi Output String is - %s \n", str);
int i=0;
while(str[i]!='\0')
{
start = i;
for(; str[i]!='+'&&str[i]!='\0'&&str[i]!='-'&&str[i]!='*'&&str[i]!='/'&&str[i]!='%';i++);
end = i-1;
ReverseStringUtil(str,start,end);
i++;
}
printf("Output String is %s \n", str);
return 0;
}
def reverse_str(string)
newString= ""
strArr = string.chars
numArr = string.split(/[-,+,*,\/]/)
operatorArr = ['*', '+', '-', '/']
i = strArr.length.to_i - 1
j = numArr.length.to_i - 1
while i >= 0
a = strArr[i]
if operatorArr.include?(a)
newString = newString + "#{a}"
i = i - 1
else
b = numArr[j]
newString = newString + "#{b}"
j = j -1
i = i - b.length
end
end
puts newString
end
string = "1+2*3-20"
reverse_str(string)
string2 = "10-2*3-2000"
reverse_str(string2)
string3 = "10-2*3-+5-992000"
reverse_str(string3)
public class String1 {
public static void main(String[] args) {
String1 s = new String1();
String str = "1+2*3-20";
String sa[] = str.split("");
String ss = s.solution(sa);
System.out.println(ss);
}
public String solution(String s[]){
int l = s.length -1;
String out="";
int i=l;
while(i> -1){
String c = s[i];
int j=0;
if(!c.equals("+") || !c.equals("-") || !c.equals("*")){
j=i;
}
while (j >0){
String c1 = s[j];
if(c1.equals("+") || c1.equals("-") || c1.equals("*")){
out = out + c1;
j = 0;
}else{
out = c1 + out;
j--;
}
i--;
}
}
return out;
}
}
public class String1 {
public static void main(String[] args) {
String1 s = new String1();
String str = "1+2*3-20";
String sa[] = str.split("");
String ss = s.solution(sa);
System.out.println(ss);
}
public String solution(String s[]){
int l = s.length -1;
String out="";
int i=l;
while(i> -1){
String c = s[i];
int j=0;
if(!c.equals("+") || !c.equals("-") || !c.equals("*")){
j=i;
}
while (j >0){
String c1 = s[j];
if(c1.equals("+") || c1.equals("-") || c1.equals("*")){
out = out + c1;
j = 0;
}else{
out = c1 + out;
j--;
}
i--;
}
}
return out;
}
}
This is generic to keeping numbers as is and reversing on basis of operators.
1+2*3-20+5325/133
Ans : 133/5325+20-3*2+1
import java.util.ArrayList;
import java.util.HashSet;
public class ReverseStringsKeepNumberAsIs {
HashSet<String> hs = new HashSet<String>();
ReverseStringsKeepNumberAsIs(){
this.hs.add("+");
this.hs.add("-");
this.hs.add("*");
this.hs.add("/");
this.hs.add("%");
this.hs.add("^");
this.hs.add("\\");
}
String reversalNumSame(String str) {
// 1+2*3-20
String[] brokenStr = (str+" ").split("");
// can be used str+"".toCharArray()
// Space is being used as a end of line character
String result="",temp="";
for (String c:brokenStr) {
if ((this.hs.contains(c)) || (c.equalsIgnoreCase(" "))) {
result = c + temp + result;
temp="";
c = "";
}
temp = temp + c;
}
return result.trim();
}
// Javascript Implementation -
/**
* Reverse this string 1+2*3-20. Note: 20 must be retained as is. Expected
* output: 20-3*2+1
*/
function reverseString(str) {
let startIndex = 0;
let stack = [];
for(let i = 0, length = str.length; i < length; i++) {
const char = str[i];
if(isNaN(char)){
let subStr = str.substring(startIndex, i);
stack.push(subStr);
stack.push(str[i]);
startIndex = i+1;
}
}
if(startIndex < str.length){
let subStr = str.substring(startIndex);
stack.push(subStr);
}
return stack.reverse().join('');
}
const str = "1+2*3-20+2000+";
console.log("Before Reverse String is -> " + str);
const reverseStr = reverseString(str);
console.log("After Reverse String is -> " + reverseStr);
def reverse_arith_string(str_arith):
'''
Input Arithmetic operations and numbers as strings and reverse the string
without reversing values
Time complexity = O(N) - Linearily Traversing in string
Space complexity = O(N) - as storing the reversed string
'''
str_arith = str_arith.strip()
if str_arith == "" : return None
d_sym={'+':0,'*':0,'-':0}
str_arith_rev = ''
end_pos = len(str_arith)
for start_pos in range(len(str_arith)-1,-1,-1):
if str_arith[start_pos] in d_sym :
str_arith_rev = str_arith_rev + str_arith[start_pos + 1:end_pos] + str_arith[start_pos]
end_pos = start_pos
str_arith_rev = str_arith_rev + str_arith[0:end_pos]
return str_arith_rev
print(reverse_arith_string(" 1+2*3-20 "))
print(reverse_arith_string("1+2*3-204"))
print(reverse_arith_string("1+2*3-0"))
print(reverse_arith_string(""))
public class SplitRev
{
public static void main(String[] args)
{
String s="1+2*3-204";
String no[]=s.split("[^0-9]");
String del[]=s.split("[0-9]");
String tot[]=new String[no.length+del.length];
int k=no.length-1,l=del.length-1;
for(int i=0;i<tot.length;i++)
{
int j=i+1;
if(!(j%2==0))
{
tot[i]=no[k];
k--;
}
else
{
tot[i]=del[l];
l--;
}
}
String revSt="";
for(String st: tot)
revSt+=st;
System.out.println(revSt);
}
.
A very simple concept is to use a stack and push all the numeric values into it until we encounter an operator, if an operator is found concatenate all the numeric values to a string and pop out all the elements from the stack till it is empty, keep doing the same process until all characters in a string is traversed and finally concatenate the remaining numeric values to the string and return the string
Implementation:
#include<bits/stdc++.h>
using namespace std;
bool checkoperator(char c){
if(c == '-' || c == '+' || c == '/' || c == '*')
return true;
else
return false;
}
string reversestring(string str){
stack<char> s;
string st = "";
for(int i = str.length() - 1; i >= 0; i--){
if(checkoperator(str[i])){
while(!s.empty()){
st += s.top();
s.pop();
}
st += str[i];
}
else
s.push(str[i]);
}
while(!s.empty()){
st += s.top();
s.pop();
}
return st;
}
int main()
{
string str = "1+2*3-20456+980";
cout<<reversestring(str)<<endl;
return 0;
}
- sudip.innovates September 22, 2017