Facebook Interview Question
Front-end Software EngineersCountry: India
Interview Type: In-Person
Since the question says "use very simple code and concept(ALGORITHM)", I suppose they don't want any sophisticated like the KMP algorithm to find substring occurrences.
int RemoveSubstring(string& text, const string& sub) {
size_t pos = text.find(sub);
if (pos == string::npos)
return -1;
text.erase(pos, sub.size());
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a,b; // I will take both string input from user and check whether b is substing of a or not.
cin>>a;
cin>>b;
int idx = 0;
idx = a.find(b); // Checking whether b is substring of a.
if(idx == 0)
{
int l = b.length();
a = a.substr(l);
cout<<a<<"\n";
}
else if(idx > 0)
{
int l = b.length();
string temp="";
temp = a.substr(0,idx);
a = a.substr(idx+l);
cout<<temp<<a<<"\n";
}
else
{
cout<<"-1\n";
}
return 0;
}
This is incorrect. Note that for input "ZABCSC" and substring "ABC" the string becomes "ZSC".
Thanks for pointing out my mistake.
I was missing such case. I edited for my answer considering all possibilities, please have a look.
By the way i have only this code into my previous code
else if(idx > 0)
{
int l = b.length();
string temp="";
temp = a.substr(0,idx);
a = a.substr(idx+l);
cout<<temp<<a<<"\n";
}
JavaScript
(function(){ alert(checkString("ABCSC")); })();
function checkString(s){
return /ABC/.test(s) ? s.replace(/ABC/g,"SC") : -1
}
Examples: "zabcaabcbcs" should result "zs" , if there is multiple existence of substring.
can be done very simply in java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class removeSubStr {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sf = new StringBuffer();
System.out.println("Enter main String:");
sf.append(br.readLine());
System.out.println("Enter substring to search:");
String subStr = br.readLine();
if(removeSubString(sf,subStr) == -1)
System.out.println("Substr not found");
else
System.out.println("replaced string is: " + sf.toString());
}
static int removeSubString(StringBuffer mainStr, String subStr)
{
String strCopy = mainStr.toString();
while(mainStr.indexOf(subStr) >= 0)
{
mainStr.delete(mainStr.indexOf(subStr),mainStr.indexOf(subStr)+ subStr.length());
System.out.println(mainStr.toString()); //intermediate results
}
if(strCopy.equals(mainStr.toString()))
return -1;
else
return 0;
}
}
Well here is a code written very easily in Python 3.3.2, have a look :)
def string():
a=input("Enter the string: ")
b=input("Enter the substring: ")
print("The strings are :",a,b)
if b in a:
print("After removing the substring: ",a.replace(b,''))
else:
return -1
<?php
function search($string, $keyword)
{
for($i = 0;$i<strlen($string);$i++)
{
for($j = 0;$j<strlen($keyword);$j++)
{
if($tmp===$keyword) break;
if(substr($string,$i,1) === substr($keyword,$j,1))
{
$tmp = $tmp.substr($string,$i,1);
$string = substr_replace($string,"",$i,1);
}
}
}
if(empty($tmp)||trim($tmp)!=trim($keyword)){
return -1;
} else {
return $string;
}
}
//Main
echo"String-> ";
$string = trim(fgets(STDIN));
echo"Keyword-> ";
$keyword = trim(fgets(STDIN));
echo "Result-> ".search($string,$keyword)."\n";
public class Main {
public static void main(String[] args) {
String string = "ABCSC";
String substring = "ABC";
System.out.println(containsSubString(string, substring));
}
public static String containsSubString(String string, String substring){
if (string.contains(substring)){
int leftIndex = string.indexOf(substring);
int rightIndex = leftIndex + substring.length();
StringBuilder stringBuilder = new StringBuilder(string);
stringBuilder.replace(leftIndex, rightIndex, "");
return stringBuilder.toString();
}
return Integer.toString(-1);
}
}
<!DOCTYPE html>
<html>
<head>
<script type=text/javascript>
var str="ABCSC";
reg=/ABC/;
if(reg.exec(str))
str=str.replace("ABC", "");
else
return -1;
document.write(str);
</script>
</head>
<body>
</body>
</html>
// with help of RegExp
function check(str, pattern) {
'use strict';
var reg = new RegExp(pattern, 'g');
if (reg.test(str) === false) {
return -1;
} else {
var l = pattern.length;
var i = str.indexOf(pattern);
return str.slice(0, i) + str.slice(i + l);
}
}
// without using RegExp
function vanillaCheck(str, pattern) {
'use strict';
var i = 0;
var l = str.length;
var result = -1;
while (i <= l - pattern.length) {
var s = str.slice(i, i + pattern.length);
if (s === pattern) {
result = str.slice(0, i) + str.slice(i + s.length);
break;
}
++i;
}
return result;
}
var s = 'ABCSC';
console.log(check(s, 'BC'));
console.log(vanillaCheck(s, 'BC'));
import java.util.*;
class SubString
{
public static void main(String args[])
{
Scanner src = new Scanner(System.in);
while(src.hasNextLine())
{
String str = src.nextLine();
String sub = src.nextLine();
if(str.contains(sub))
{
str = str.replace(sub,"");
System.out.println(str);
}
else if(!str.contains(sub))
{
System.out.println("-1");
}
}
}
}
call remove function recursively removing the subtext. not the best solution, but easy to understand.
public static void main(String args[])
{
String s = "ABCSC";
String r = "ABC";
System.out.println(remove(s, r));
}
public static String remove(String s, String r)
{
if(s.indexOf(r) == -1) //removed all
return s;
int index = s.indexOf(r);
String processed = s.substring(0, index)
+ s.substring(index+r.length(), s.length());
return remove(processed, r);
}
Not the best solution, but easy to understand.
public static void main(String args[])
{
String s = "ABCSC";
String r = "ABC";
System.out.println(remove(s, r));
}
public static String remove(String s, String r)
{
if(s.indexOf(r) == -1) //removed all
return s;
int index = s.indexOf(r);
String processed = s.substring(0, index)
+ s.substring(index+r.length(), s.length());
return remove(processed, r);
}
I don't remember if this the KMP algorithm but I think is similarly good as it is O(n) solution worst case would be O(n^2) if there are always hash-code collisions.
public static bool SubStringExist(string S, string subStr)
{
long hahs = 0;
foreach(char c in subStr)
hash += c.GetHashCode();
// Not needed but using for ease of understanding
int head = 0;
int tail = 0;
long sHash = 0;
for(; tail < S.Length; tail++)
sHash += S[tail].GetHashCode();
for(; tail < S.Length; tail++)
{
if(hash == strHash)
{
// Verify in case of hash collisions
bool equal = true;
for(int j = head; j < tail; j++)
{
if(S[j] != subStr[j-head])
{
equal = false;
break;
}
}
if(equal)
{
return true;
}
}
sHash += S[tail].GetHashCode() - S[head].GetHashCode();
head++;
}
}
Very simple problem. This is the JavaScript solution, whose worst case performance is o(n).
<script>
function isSubString(sourceStr, subStr, sourceIndex, subStrIndex) {
if (sourceIndex >= sourceStr.length) {
return -1;
}
if (subStrIndex >= subStr.length) {
var res = sourceStr.substr(0, sourceIndex - (subStr.length - 1));
if (sourceIndex < sourceStr.length - 1) {
res += sourceStr.substr(sourceIndex + 1);
}
return res;
}
++ sourceIndex;
if (sourceStr.charAt(sourceIndex) == subStr.charAt(subStrIndex)) {
++subStrIndex;
return isSubString(sourceStr, subStr, sourceIndex, subStrIndex);
} else {
return isSubString(sourceStr, subStr, sourceIndex, 0);
}
}
alert(isSubString("xabc", "abc", 0, 0)); //x
alert(isSubString("ababbabcd", "abc", 0, 0)); //ababbd
alert(isSubString("ababbabcd", "abd", 0, 0)); //-1
alert(isSubString("ababbabcd", "bcd", 0, 0)); //ababba
alert(isSubString("ababbabcd", "ccd",0, 0)); //-1
alert(isSubString("ababbabcd", "bba", 0, 0)); //ababcd
</script>
public class SubStringFind {
public static String findStr(String mainString, String subString) {
if (mainString.contains(subString)) {
return mainString.replace(subString, "");
} else {
return "-1";
}
}
public static void main(String[] args) {
String result = SubStringFind.findStr("ABCSC", "ABC");
System.out.println(result);
}
}
console.log(findSubstring('TRABCSC', 'ABC'));
function findSubstring(text, substring) {
let index=0;
for(let i=0;i<text.length;i++){
if (substring[index]==text[i]) {
if(index == substring.length-1)
{
return trimString(text, i-substring.length+1, substring.length);
}
index++;
}else{
index = 0;
}
}
return -1;
}
function trimString(text, start, length){
let s='';
for(let i=0;i<start;i++){
s+= text[i];
}
for(let i=start+length;i<text.length;i++){
s+= text[i];
}
return s;
}
var string = "ABCSC";
- sethtoda November 14, 2013((string.indexOf("ABC") != -1) ? (string.replace(/ABC/gm,"")) : (-1));