Booking.com Interview Question
Software DevelopersCountry: Netherlands
Interview Type: Phone Interview
{{
public String makeSmartString(String str) {
if (str.length() <= 30) {
return str;
}
String smartStr = str.substring(0, 30);
for (int i = smartStr.length()-1; i >0; i--) {
if (smartStr.charAt(i) == ' ') {
return smartStr.substring(0, i);
}
}
return smartStr;
}
}}
public class String1 {
public static void main(String[] args) {
String s1="Featuring stylish rooms and moorings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.";
String result=getFullString(s1,30);
System.out.println(result);
}
private static String getFullString(String s1,int i) {
String[] str=s1.split(" ");
StringBuilder sb=new StringBuilder();
int charCount=0;
for (String string : str) {
charCount=charCount+string.length()+1;
if(charCount <= i){
sb.append(string+" ");
}
}
return sb.toString().trim();
}
}
Here is the Code in PHP
<?php
function smartString($s)
{
$str=substr($s,0, 30);
$e=explode(" ",$s);
$output=explode(" ",$str);
for($i=0;$i<count($output);$i++)
{
if(strcmp($output[$i],$e[$i])!=0)
{
$diff=strlen($e[$i])-strlen($output[$i]);
$total= strpos($str,$output[$i])+strlen($e[$i]);
if($diff > 2)
{
echo substr($str,0,strpos($str,$output[$i]))."<br/>";
}
elseif($diff <= 2) {
echo substr($s,0,$total)."<br/>";
}
}
}
//echo $str;
}
smartString("Featuring stylish rooms and moornings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.")
?>
PHP
<?php
function smartString($s)
{
$str=substr($s,0, 30);
$e=explode(" ",$s);
$output=explode(" ",$str);
for($i=0;$i<count($output);$i++)
{
if(strcmp($output[$i],$e[$i])!=0)
{
$diff=strlen($e[$i])-strlen($output[$i]);
$total= strpos($str,$output[$i])+strlen($e[$i]);
if($diff > 2)
{
echo substr($str,0,strpos($str,$output[$i]))."<br/>";
}
elseif($diff <= 2) {
echo substr($s,0,$total)."<br/>";
}
}
}
//echo $str;
}
smartString("Featuring stylish rooms and moornings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.")
?>
In my approach, I tried to find the maximum number of characters in the string without breaking the words which is nearer to 30 but not just the first 30 characters of the string, but searching the entire string for the maximum number of characters.
{{
private static String SmartSubstring(String str, int cuttingIndex){
String maxSubString=" ";
int max=0;
while(str.length()>=cuttingIndex) {
String smartStr = str.substring(0, cuttingIndex);
str=str.substring(str.indexOf(" ",0)+1);
smartStr = smartStr.substring(0, smartStr.lastIndexOf(" "));
if(smartStr.length()>max){
max=smartStr.length();
maxSubString=smartStr.trim();
}
}
return maxSubString+"-"+maxSubString.length();
}
}}
import java.util.*;
import java.lang.*;
public class smart{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
String str=s.nextLine();
char[] c=str.toCharArray();
char[] d=new char[str.length()];
String[] sa=str.split(" ");
int count=0;
for(int i=0;i<30;i++){
if(c[i]==' '){
count=count+1;
}
}
for(int j=0;j<=count;j++){
System.out.println(sa[j]);
}
}
import java.util.*;
import java.lang.*;
public class smart{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
String str=s.nextLine();
char[] c=str.toCharArray();
char[] d=new char[str.length()];
String[] sa=str.split(" ");
int count=0;
for(int i=0;i<30;i++){
if(c[i]==' '){
count=count+1;
}
}
for(int j=0;j<=count;j++){
System.out.println(sa[j]);
}
}
public class SmartSubString {
public static void main(String[] args) {
String s = "Featuring boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.";
System.out.println("SubString: " + findSmartSubString(s.substring(0, 43).toString()));
}
public static String findSmartSubString(String s){
for(int i = s.length()-1;i>0;i--){
if(s.charAt(i) == ' ' || s.charAt(i) == '.' || s.charAt(i) == ','){
return s.substring(0,i).toString();
}
}
return s;
}
}
public class SmartSubString {
public static void main(String[] args) {
String s = "Featuring boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.";
System.out.println("SubString: " + findSmartSubString(s.substring(0, 43).toString()));
}
public static String findSmartSubString(String s){
for(int i = s.length()-1;i>0;i--){
if(s.charAt(i) == ' ' || s.charAt(i) == '.' || s.charAt(i) == ','){
return s.substring(0,i).toString();
}
}
return s;
}
}
private static String getSmartSubString(String message){
if(message == null){
return "";
}
if(message.length()<=30){
return message;
}
else{
String s30 = message.substring(0, 31);
// take substring upto 31st character in input string
String subStr = message.substring(0, 32);
//check if last char in substring is alphabet or number
if(!isAlphaOrNum(subStr.charAt(31))){
//if not alphabet or number, check if its one of the predefined symbols that are supposed to separate two sentences
if(isSymbol(subStr.charAt(31))){
return subStr.substring(0, 31);
}
}
else{
for(int i = subStr.length()-1; i>=0; i--){
if(isSymbol(subStr.charAt(i))){
return subStr.substring(0, i);
}
}
}
}
return "";
}
private static boolean isAlphaOrNum(char ch){
boolean alpha = (ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A');
boolean num = (ch <= '9' && ch >= '0');
if(alpha || num){
return true;
}
return false;
}
private static boolean isSymbol(char ch){
char[] symbols = {',', '.', ';', '!', ' '};
for(char c : symbols){
if(c == ch){
return true;
}
}
return false;
}
private static String getSmartSubString(String message){
if(message == null){
return "";
}
if(message.length()<=30){
return message;
}
else{
String s30 = message.substring(0, 31);
// take substring upto 31st character in input string
String subStr = message.substring(0, 32);
//check if last char in substring is alphabet or number
if(!isAlphaOrNum(subStr.charAt(31))){
//if not alphabet or number, check if its one of the predefined symbols that are supposed to separate two sentences
if(isSymbol(subStr.charAt(31))){
return subStr.substring(0, 31);
}
}
else{
for(int i = subStr.length()-1; i>=0; i--){
if(isSymbol(subStr.charAt(i))){
return subStr.substring(0, i);
}
}
}
}
return "";
}
private static boolean isAlphaOrNum(char ch){
boolean alpha = (ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A');
boolean num = (ch <= '9' && ch >= '0');
if(alpha || num){
return true;
}
return false;
}
private static boolean isSymbol(char ch){
char[] symbols = {',', '.', ';', '!', ' '};
for(char c : symbols){
if(c == ch){
return true;
}
}
return false;
}
private static String getSmartSubString(String message){
if(message == null){
return "";
}
if(message.length()<=30){
return message;
}
else{
String s30 = message.substring(0, 31);
// take substring upto 31st character in input string
String subStr = message.substring(0, 32);
//check if last char in substring is alphabet or number
if(!isAlphaOrNum(subStr.charAt(31))){
//if not alphabet or number, check if its one of the predefined symbols that are supposed to separate two sentences
if(isSymbol(subStr.charAt(31))){
return subStr.substring(0, 31);
}
}
else{
for(int i = subStr.length()-1; i>=0; i--){
if(isSymbol(subStr.charAt(i))){
return subStr.substring(0, i);
}
}
}
}
return "";
}
private static boolean isAlphaOrNum(char ch){
boolean alpha = (ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A');
boolean num = (ch <= '9' && ch >= '0');
if(alpha || num){
return true;
}
return false;
}
private static boolean isSymbol(char ch){
char[] symbols = {',', '.', ';', '!', ' '};
for(char c : symbols){
if(c == ch){
return true;
}
}
return false;
}
PYTHON Script
def smartString(st):
l = len(st)
print ('Total characters in string: ' + str(l))
if (l <= 30):
returnString = st
else:
for i in range (0, l):
if (st[i] == ' ' and i <= 30):
returnString = st[0:i]
print (returnString)
smartString("this is a string with many words and # of characters > 30")
#include <iostream>
#include <string>
using namespace std;
string SmartSubstring30Chars(string test, unsigned int limit)
{
if(test.length() <= limit)
return test;
string result;
size_t end = 0;
size_t begin = 0;
do{
end = test.find(" ", begin);
if(end != string::npos)
{
result += (test.substr(begin, end - begin) + " ");
begin = end + 1;
}
}while(end <= limit);
return result;
}
int main()
{
string test = "Featuring stylish rooms and moorings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.";
string result = SmartSubstring30Chars(test, 200);
cout << result << endl;
return 0;
}
Java -
public class SmartSubString {
public String checkThirty(String str, int n){
String subString = str.substring(0, n);
int counter= n;
if(Character.isWhitespace(str.charAt(n))){
System.out.println(subString);
return subString;
}
if(! Character.isWhitespace(str.charAt(n))){
for(int iii= subString.length(); iii>0; iii--){
while(Character.isWhitespace(str.charAt(iii))){
String subString2 = subString.substring(0, iii);
System.out.println(subString2);
counter = iii;
return subString2;
}
}
}
System.out.println(subString);
return str.substring(0, counter);
}
public static void main(String []args){
SmartSubString smarty = new SmartSubString();
smarty.checkThirty("Featuring stylish rooms and moorings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.", 30);
}
}
Complete Java solution with considering different edge cases
import java.util.*;
import java.io.*;
public class Solution {
/*
Smart string is a string no longer than 30 character with cut no words
*/
public static void main(String[] args) {
new Solution().solve();
}
public void solve() {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = in.nextLine();
String res = s;
int maxLen = 10;
int firstSpace = s.indexOf(" "); // whole sentence is one word and it's longer than max allowed
if (firstSpace > maxLen)
res = "";
else if (s.length() > maxLen) {
String cutStr = s.substring(0, maxLen);
res = cutStr.substring(0, Math.max(cutStr.lastIndexOf(" "), cutStr.length()));
}
out.print(res);
out.close();
}
}
public String smartSubString(String str, int length) {
int i = length-1;
while(!isWordEnd(str, i)) {
i--;
}
return str.substring(0, i+1);
}
private boolean isWordEnd(String str, int index) {
char ch = str.charAt(index);
if(ch == '.' || ch == '!' || ch == '?' || ch == ',' || ch == ';') {
return true;
} else if(ch != ' ') {
if(index == str.length()-1) {
return true;
} else {
if(str.charAt(index + 1) == ' ') {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
if (string.IsNullOrEmpty(full))
{
return null;
}
List<int> spaces = new List<int>();
spaces.Add(0);
for (int i = 0; i < full.Length; i++)
{
if (full[i] == ' ')
{
spaces.Add(i);
}
}
string result = "";
int index = 0;
while (total >= 0&& index < spaces.Count)
{
if (result.Length + full.Substring(spaces[index], spaces[index + 1] - spaces[index]).Length < total)
{
result += full.Substring(spaces[index], spaces[index + 1] - spaces[index]);
index++;
}
else
{
break;
}
}
return result;
public class SmartSubstring {
public static String smartSub(String s, int start, int end) {
if (start != 0) {
if (s.charAt(start) != ' ' || s.charAt(start - 1) != ' ') {
while (start < end) {
if (s.charAt(start) == ' ') {
break;
}
start++;
}
start = start + 1;
}
}
if (end != (s.length() - 1)) {
if (s.charAt(end) != ' ' || s.charAt(end + 1) != ' ') {
while (start < end) {
if (s.charAt(end) == ' ') {
break;
}
end--;
}
}
}
if (end >= start) {
return s.substring(start, end);
} else {
return null;
}
}
public static void main(String[] args) {
String s = "Featuring stylish rooms and moorings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.";
int start = 0;
int end = 30;
System.out.println("Smart SubString:" + smartSub(s, start, end));
System.out.println("Default SubString:" + s.substring(start, end));
}
}
Solution in perl:
my $str = "Featuring stylish rooms and moorings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.";
my @res = ();
for my $word (split '\s+', $str) {
if (length (join ' ', @res) + (length $word) + 1 > 30) {
last;
} else {
push @res, $word;
}
}
print join ' ', @res;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
int limit = scan.nextInt();
scan.close();
if (str.length() > limit ) {
str = str.substring(0, limit+1);
try {
if (!str.endsWith(" ")) {
str = str.substring(0, str.lastIndexOf(" "));
}
} catch (StringIndexOutOfBoundsException e) {
str = "";
}
}
System.out.println("Output "+str);
}
public static List<String> subString(String originStr, int length) {
String[] str = originStr.split(" ");
int[][] dp = new int[str.length][length + 1];
boolean[][] used = new boolean[str.length][length + 1];
for (int i = 0; i <= length; i++) {
if (i >= str[0].length()) {
dp[0][i] = str[0].length();
used[0][i] = true;
}
}
for (int i = 1; i < str.length; i++) {
for (int j = 0; j <= length; j++) {
int currentLength = str[i].length();
if (currentLength > j) {
dp[i][j] = dp[i - 1][j];
used[i][j] = false;
} else {
int i1 = dp[i - 1][j];
int i2 = dp[i - 1][j - currentLength] + currentLength;
if (i1 > i2) {
dp[i][j] = i1;
used[i][j] = false;
} else {
dp[i][j] = i2;
used[i][j] = true;
}
}
}
}
int max = Integer.MIN_VALUE;
int startI = 0;
int startJ = 0;
for (int i = 0; i < str.length; i++) {
for (int j = 1; j <= length; j++) {
if (dp[i][j] > max) {
startI = i;
startJ = j;
max = dp[i][j];
}
}
}
List<String> res = new LinkedList<>();
for (int i = startI; i >= 0; i--) {
if (used[i][startJ]) {
res.add(str[i]);
startJ -= str[i].length();
}
}
return res;
}
public class Wow {
public static void main (String args[]) {
System.out.println(new Wow().solve("Featuring stylish rooms and moornings for recreation"));
System.out.println(new Wow().solve("Featuring stylish rooms roma o ornings for recreation"));
}
public String solve(String string) {
if (string.length() <= 30)
return string;
return solve(string, 30);
}
private String solve(String string, int index) {
if (index < 1)
return "";
if (string.charAt(index-1) == ' ')
return string.substring(0, index);
return solve(string, --index);
}
}
Python:
s = 'Featuring stylish rooms and mornings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.'
n = 30
#First 30 characters:
#"Featuring stylish rooms and mo"
#output = "Featuring stylish rooms and"
def smartcheck(s,n):
len1 = len(s)
if len1 <= n:
return s
s1 = ''
if s[n] == ' ' or s[n] == ',' or s[n] == '.':
for i in range(0,n):
s1 = s1+s[i]
return s1
for i in range (n-1,-1,-1):
print s[i]
if s[i] == ' ' or s[i] == ',' or s[i] == '.':
temp = i
break
for i in range(0,temp):
s1 = s1 + s[i]
return s1
s1 = smartcheck(s,n)
print s1
/*
"Smart substring"
Write a function that takes maximum 30 characters from a string but without cutting the words.
Example
30
Featuring stylish rooms and moorings for recreation boats, Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.
First 30 characters:
"Featuring stylish rooms and mo"
Smarter approach (max 30 characters, no words are broken):
"Featuring stylish rooms and"
*/
import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.regex.*;
class GFG {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int maxChars = scan.nextInt();
scan.nextLine();
String str = scan.nextLine();
System.out.println(smartString(str, maxChars));
}
public static String smartString(String str, int maxChars) {
StringBuffer smartStr = new StringBuffer();
StringBuffer currentWord = new StringBuffer();
for(char c : str.toCharArray()) {
if(c == ' ' || c == '\r' || c == '\n') {
if(currentWord.length() > 0) {
if(smartStr.length() + currentWord.length() <= maxChars) {
smartStr.append(currentWord);
currentWord.setLength(0);
} else {
break;
}
}
}
currentWord.append(c);
}
return smartStr.toString();
}
}
We just need the index upto which we need to print the sub-string.
2 Solutions:
1) Since its a string, exact index access is possible. Loop through the string and reach exact 30th index. Check the 31st index.. If its space, ans is 1 to 30 characters. Else, loop back to find the index containing the space. Letys say its N, answer is 1 to Nth index of string.
2) Loop from start index, mark and store the end of last word countered. Hence, at 30th index, if the next index is not space, Marked value is answer(1 to Marked index). Else, answer is 1 to 30th index
public class FindSmartSubstring {
public static void main(String[] args) {
// TODO Auto-generated method stub
String subString = "Featuring stylish rooms and moornings for recreation boats,"
+ " Room Mate Aitana is a designer hotel built in 2013 on an island in the IJ River in Amsterdam.";
System.out.print(findSmartString(subString,30));
}
static String findSmartString(String s,int length) {
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
int total = 0;
for(String str:arr) {
total = total + str.length();
if(total > length)
break;
sb.append(str+" ");
}
return sb.toString();
}
}
Here is my solution in C#.
- ersegun August 22, 2015