Interview Question
Country: United States
class MyQueue(object):
def __init__(self, my_str):
self.queue = list(my_str)
self.back_queue = []
self.back_queue_len = 0
self.__handler()
def __handler(self):
"""
we firstly get all non-digit words. put them into another list(back_queue)
with its postion.then replace the words in queue with position in back_queue
"""
for i in xrange(len(self.queue)):
if not self.__check_digit(self.queue[i]):
self.back_queue.append(i)
self.back_queue_len = len(self.back_queue)-1
for i in xrange(int(len(self.back_queue)/2)):
self.__exchange(self.back_queue[i], self.back_queue[self.back_queue_len-i])
def __exchange(self, index_a, index_b):
temp = self.queue[index_a]
self.queue[index_a] = self.queue[index_b]
self.queue[index_b] = temp
def __check_digit(self, elem):
return elem in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def get_result(self):
return "".join(self.queue)
if __name__ == "__main__":
#import pdb
#pdb.set_trace()
my_str = "ni2qadaefadf8d67a67da6d86a7ed7a87f89ea7f7a9f79ae79f8e79a87f345"
print "before:",my_str
my_queue = MyQueue(my_str)
print "after:", my_queue.get_result()
public static String reverseString(String s) {
//base case
if(s == null || s.length() <= 1) {
return s;
}
char[] arr = s.toCharArray();
int k = arr.length-1;
int i = 0;
while(i < k) {
if(arr[i] >= '0' && arr[i] <= '9') { i++; }
if(arr[k] >= '0' && arr[k] <= '9') { k--; }
if (i < k) {
//swap the elements
char temp = arr[i];
arr[i] =arr[k];
arr[k] = temp;
}
i++; k--;
}
return String.valueOf(arr);
}
I think the example output is incorrect. If the numbers are suppose to be in the same position, then the '3' at the end of the output string is in the incorrect place. In addition, it is unclear what happens when a letter should be swapped with a number. Do both the letter and the number stay in the same place? Or does the letter get swapped with the next possible letter? I list both outputs below
Input: str1ngw1thnumb3rs
Output as listed: srb1mun1htwgn3rts
Corrected output if letter/number pairs stay in the same place: srr1mun1thwgnb3ts
Corrected output if we remove the numbers, reverse the string, and re-insert numbers: srb1mun1htwgnr3ts
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringReverse {
public static void main(String[] args) {
String str= "str90ngw1thnumb3rs";
StringBuilder withoutnum = new StringBuilder();
Map<Integer,String> map = new HashMap<>();
Pattern pat = Pattern.compile("\\d+");
Matcher match = pat.matcher(str);
while(match.find())
{
map.put(match.start(), match.group());
}
Pattern pat1 = Pattern.compile("[a-z]");
Matcher match1 = pat1.matcher(str);
while(match1.find())
{
withoutnum.append(match1.group());
}
Iterator it = map.keySet().iterator();
while(it.hasNext())
{
int i=(int) it.next();
withoutnum.reverse().insert(i, map.get(i));
}
System.out.println(withoutnum.toString());
}
}
def process_str(input_str):
digit_index_list = [i for i in range(0,len(input_str)) if input_str[i].isdigit()]
alpha_list_reversed = [c for c in input_str[::-1] if c.isalpha()]
output_list = alpha_list_reversed
for i in digit_index_list:
output_list.insert(i, input_str[i])
return "".join(output_list)
I think the example output is wrong.
public static String swapString(String str)
{
char[] charArr = str.toCharArray();
int len = charArr.length, leftP = 0, rightP = len-1;
while( leftP < rightP)
{
if(charArr[leftP] < '0' || charArr[leftP] > '9')
{
while((charArr[rightP] >= '0') && (charArr[rightP] <='9')) {--rightP;}
swap(charArr, leftP, rightP);
--rightP;
}
++leftP;
}
return new String(charArr);
}
In C++:
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
string& reverseLetters(string& dest, const string& src)
{
dest.clear();
dest.resize(src.size());
for(int i = 0, j = src.size() - 1; j >= 0; ){
if(isdigit(src[i])){
dest[i] = src[i];
++i;
}
else if(isdigit(src[j])) --j;
else{
dest[i] = src[j];
++i;
--j;
}
}
return dest;
}
int main()
{
string t, s = "str1ngw1thnumb3rs";
cout << reverseLetters(t, s) << "\n";
getchar();
return 0;
}
public static String reverse(String str){
char[] arr = str.toCharArray();
int start = 0;
int end = arr.length-1;
while(start<end){
while( arr[start] >= '0' && arr[start] <= '9'){
if( start == end)break;
start++;
}
while( arr[end] >= '0' && arr[end] <= '9'){
if( start == end)break;
end--;
}
if(start<end){
arr[start] ^= arr[end];
arr[end] ^= arr[start];
arr[start] ^= arr[end];
start++;
end--;
}
}
return new String(arr);
}
public static void main(String[]args){
///test cases
String str = new String("str1ngw2thnumb3rs");
System.out.println(" Input : str :" + str+ " Output = "+ reverse(str));
System.out.println(" Input : str :" + "1111"+ " Output = "+ reverse("1111"));
System.out.println(" Input : str :" + "1234a"+ " Output = "+ reverse("1234a"));
System.out.println(" Input : str :" + "a1234"+ " Output = "+ reverse("a1234"));
System.out.println(" Input : str :" + "abc1234"+ " Output = "+ reverse("abc1234"));
System.out.println(" Input : str :" + "abcd1234"+ " Output = "+ reverse("abcd1234"));
System.out.println(" Input : str :" + "abcd"+ " Output = "+ reverse("abcd"));
System.out.println(" Input : str :" + ""+ " Output = "+ reverse(""));
}
void reverseSpec(std::string& in, std::string &final)
{
final = in; // this way digits stay in place
std::string tmp;
for (int i = in.length()-1, j = 0; i >= 0; i--)
{
// if it is alpha add it to our temp but reversed
if (isdigit(final[j]))
++j;
if (isalpha(in[i]) || isspace(in[i]))
{
final[j] = in[i];
j++;
}
}
}
void testFancyRev()
{
std::string input("vla1do1cavise3jp");
std::string out;
reverseSpec(input, out);
std::cout << "in: " << input << std::endl;
std::cout << "out: " << out << std::endl;
}}
public static String reverse(String str){
char ch[] = str.toCharArray();
int start = 0;
int end = str.length() -1;
while(start<end){
boolean isStartNum =Character.isDigit(ch[start]);
boolean isEndNum =Character.isDigit(ch[end]);
if(isStartNum) ++ start;
if(isEndNum) -- end;
if(!isStartNum && !isEndNum){
char temp= ch[start];
ch[start]=ch[end];
ch[end]= temp;
++start;
--end;
}
}
return String.valueOf(ch);
}
A javascript solution
reverse = function(str){
out = "";
numbersArray = [];
for(i=(str.length-1); i>-1; i--){
if(parseInt(str[i]) == str[i]){
numbersArray.push({num: str[i], pos: i});
}else{
out += str[i];
}
}
numbersArray.forEach(function(val, index){
console.log(val)
pos = val.pos + index - 2
out = [out.slice(0, pos), val.num, out.slice(pos)].join('');
});
return out;
}
/*
Write a function accepting a string with numbers and letters that reverses the
letters of the string but leave numbers in the same position.
Example input: str1ngw1thnumb3rs
Example output:srb1mun1htwgn3rts
*/
import java.util.*;
import java.lang.*;
class stringrevdemo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s;
System.out.print("Enter the String:");
s=sc.next();
System.out.print("------------------\n");
System.out.println("Input:"+s);
char[] ch=new char[s.length()];
char[] ch1=new char[s.length()];
ch=s.toCharArray();
int j=0;
for(int i=s.length()-1;i>=0;i--)
{
if(Character.isDigit(ch[i]))
{
continue;
}
else
{
ch1[j]=ch[i];
j++;
}
}
j=0;
for(int i=0;i<s.length();i++)
{
if(Character.isDigit(ch[i]))
{
continue;
}
else
{
ch[i]=ch1[j];
j++;
}
}
System.out.print("Output:");
for(int i=0;i<s.length();i++)
{
System.out.print(ch[i]);
}
System.out.println();
}
}
Code not checked:
string reverseLettersOnly(string S){
int start = 0, end = S.length()-1;
while(start < end){
while((start <S.length()) and (0 <= S[start] - '0') and (S[start] - '0' <=9)) start++;
while((end >=0) and (0 <= S[end] - '0') and (S[end] - '0' <=9)) end--;
if (start <end) swap(S[start], S[end]);
start++;
end--;
};
return S;
};
- Matt March 19, 2014