Google Interview Question
SDE1sCountry: United States
public class Main {
public static void main(String[] args) {
System.out.println(check("ABD","BAD"));
}
static int check(String S, String D){
int i=S.length()-1;
int j=D.length()-1;
int result=0;
while(i>0 && j>0){
char s=S.charAt(i);
char d=D.charAt(j);
if(s==d){
i--;
j--;
continue;
}
result++;
i--;
}
return result;
}
}
public static int minimumTurns(String s, String t){
if(s.length() != t.length())
return -1;
if(s.equals(t))
return 0;
int index = t.length()-1;
while(index >= 0 && s.charAt(index) == t.charAt(index))
index--;
if(t.charAt(index) == s.charAt(0))
return index;
else
return index + 1;
}
Returns correct results for the following test cases:
public static void main(String[] args) {
System.out.println("expected 2 | moves count " + countMoves("abc", "cba"));
System.out.println("expected 3 | moves count " + countMoves("abc", "acb"));
System.out.println("expected 1 | moves count " + countMoves("abc", "bac"));
System.out.println("expected 0 | moves count " + countMoves("abc", "abc"));
System.out.println("expected 3 | moves count " + countMoves("abcd", "cbda"));
System.out.println("expected 2 | moves count " + countMoves("abcd", "cbad"));
}
public static int countMoves(String src, String dst) {
int count = 0;
List<Character> list = new ArrayList<>();
for (char c : src.toCharArray()) list.add(c);
boolean bWasSrcModified = false;
for (int i = dst.length() - 1; i >= 0; i--) {
char dstChar = dst.charAt(i);
int listIndex = list.lastIndexOf(dstChar);
if (listIndex == 0) {
bWasSrcModified = true;
continue;
}
if (!bWasSrcModified && listIndex == i) continue;
list.add(0, dstChar);
bWasSrcModified = true;
count++;
}
return count;
}
int Func2()
- leonzakaim February 01, 2018{
char source[] = "abc";
char search[] = "cba";
std::vector<std::vector<std::string>> stringsCount;
int lenght = strlen(source);
int i = 0;
char *ss = new char[lenght + 1]{'\0'};
for (int j = 1; j < lenght; j++)
{
strcpy_s(ss,sizeof(char)*lenght+1, source);
std::vector < std::string> strings;
for (i = 0; i<lenght; i += j)
{
char temp = ss[0];
ss[0] = ss[i];
ss[i] = temp;
strings.push_back(std::string(ss));
if (!strcmp(ss, search))
{
stringsCount.push_back(strings);
break;
}
}
}
if (stringsCount.size() > 0)
{
int min = stringsCount[0].size();
for (int i=0; i < stringsCount.size(); i++)
{
if (min>stringsCount[i].size())
min = stringsCount[i].size();
}
return min;
}
return -1;
}