Booking.com Interview Question for Software Developers


Country: Netherlands
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
3
of 3 vote

Here is my solution in C#.

private static string SmartSubstring(string str, int cuttingIndex)
        {
            string smartStr = str.Substring(0, cuttingIndex);
            smartStr = smartStr.Substring(0, smartStr.LastIndexOf(" "));
            return smartStr.Trim();
        }

- ersegun August 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 vote

{{
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;
}
}}

- Anonymous August 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Using substring inside for loop makes it O(n2) when limit = size of string

- Anonymous October 29, 2020 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Using

subString

inside

for-loop

can give

O(n2)

in worst case when limit ~ size of string

- Rajan October 29, 2020 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

def process_string(text, number):
	text_arr = text.split(" ")
	final_string = ""
	for text_val in text_arr:
		if (len(text_val) + len(final_string)) > number:
			return final_string
		final_string = (final_string + " " + text_val).strip()
	return final_string

- Kalyan Vishnubhatla August 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

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();
}

}

- bukun.cool60 September 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{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;
}}}

- Anonymous August 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.")

?>

- Mainak Ray August 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.")

?>

- Mainak Ray August 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
}
}}

- Chaitanya August 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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]);
}

}

- abhijeet September 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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]);
	}

	}

- abhijeet September 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
	}
}

- Milind Shah September 15, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
	}

}

- Milind September 15, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
	}

- ashish September 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
	}

- ashish September 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
	}

- ASHISH12021 September 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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")

- KeyurPatel September 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#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;
}

- benxavior October 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
		
	}
	
}

- akshay talathi October 15, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
    }
}

- megido December 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

с# recursive implementation.

private static string GetSmartSubstr( string str, int n ) {
    if ( n > str.Length || n == 0 ) {
        return null;
    }
    if ( n > 0 && ( str.Length == n  || str[ n ] == ' ' ) ) {
        return str.Substring( 0, n );
    }
    return GetSmartSubstr( str, --n );
}

- zr.roman December 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def smartstr(input, n)
  x = (0..n).detect do |i|
    input[n - i] == " "
  end
  input[0, n - x]
end

- fl00r January 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Might be better solution would be keep index of start of current word. As soon as you will find the count == 30, if it or next to it is not space then set this index to '/0' to terminate the string....

- Phoenix January 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
        }
    }

- Sam January 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string smartSubstr(const string& s, unsigned length) {
    if (s.length() <= length)
        return s;
    for (int i = length - 1; i >= 0; i--)
        if (s[i] == ' ')
            return s.substr(0, i);
    return "";

}

- Altay April 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string getString(string line ,int n)
{
if ( n >= line.size())
return line;

if(line[n-1] == ' ' or line[n] == ' ')
return line.substr(0,n);
else {
return line.substr(0,(line.substr(0,n)).rfind(" "));
}
}

- Anonymous May 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string getString(string line ,int n)
{
    if ( n >= line.size())
        return line;

    if(line[n-1] == ' ' or line[n] == ' ')
        return line.substr(0,n);
    else {
        return line.substr(0,(line.substr(0,n)).rfind(" "));
    }
}

- nki May 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string getString(string line ,int n)
{
    if ( n >= line.size())
        return line;

    if(line[n-1] == ' ' or line[n] == ' ')
        return line.substr(0,n);
    else {
        return line.substr(0,(line.substr(0,n)).rfind(" "));
    }
}

- nki May 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string getString(string line ,int n)
{
    if ( n >= line.size())
        return line;

    if(line[n-1] == ' ' or line[n] == ' ')
        return line.substr(0,n);
    else {
        return line.substr(0,(line.substr(0,n)).rfind(" "));
    }
}

- nki May 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;

- mark.nag June 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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));
	}
}

- cpeeyush December 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;

- Kamal Nayan December 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);

}

- tasneem March 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static String smartSubstring(String str){
		
		char[] arr=str.toCharArray();
		
		int idx=29;
		if(arr.length>30 && arr[idx] != ' '){
			
			while(idx>=0){				
				--idx;
				if(arr[idx] == ' '){					
					break;
				}
			}	
		}
		
		char[] newArr = new char[idx+1];
		System.arraycopy(arr, 0, newArr, 0, idx);
		
		return new String(newArr);
	}

- ag91375 June 19, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- Anonymous July 10, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
	}
}

- w.kinaan July 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String smartSubstring(String s) {
		while ((s = s.substring(0, s.lastIndexOf(' '))).length() > 30) {}
		return s;

- Mohamed Seif August 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python solution:

def smart_string(string, max_c):
	for i in range(max_c, 0, -1):
            if string[i] == ' ':
                return string[:i]

- Jona October 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- koolkhush February 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
"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();
	}
}

- Alex March 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- Aravind Prasad October 30, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def subText(text, limit):
    i = limit - 1
    while text[i] != " ":
        i -= 1
    return text[0:i]

- Clivern November 03, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

print(description[:30])

- Arulvalan April 26, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

print(description[:30])

- Arulvalan April 26, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String smartString(String str, int s){
		if (str.length()<30)
            return str;
        
        String substring = str.substring(0, s+1);
        char c = substring.charAt(s);
        while (c!=' '){
            s--;
            c = substring.charAt(s);
        }
        return str.substring(0,s);

}

- shubham August 10, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Simple impl

public static String getSmartSubstring(String s, int n) {
		if (s.length() < n) {
			return s;
		}

		String r = s.substring(0, n + 1);

		if (r.charAt(n) == ' ') {
			return r;
		}

		return r.substring(0, r.lastIndexOf(" "));

	}

- Arpan Khandelwal September 15, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
	}

}

- Tomas March 21, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def first30(long_str):
    if len(long_str) < 30:
        return long_str
    i = 29
    while i > 0:
        if long_str[i] == ' ':
            break
        i -= 1
    return long_str[0:i]

- Yaron P. May 04, 2021 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More