Samsung Interview Question
Senior Software Development EngineersCountry: United States
Interview Type: In-Person
Steps to solve this problem:
1) Start from the end of the string.
2) Iterate each character until an empty char.
3) When an empty char is found, keep that index and from that index to the end copy the string into temp.
4) do step 3 untill you reach start of the original string.
C# code for same;
private static void ReverseAStringByWords()
{
string s = "Reverse this string by words";
string temp = string.Empty;
int k = s.Length;
int n = 0;
for (int i = k; i >= 0; i--)
{
if (i == 0 || s[i - 1] == ' ')
{
for (int j = i; j < k; j++)
{
temp += s[j];
}
temp += ' ';
k = i;
}
}
Console.WriteLine(temp);
}
How about this, it is java.
public static void main(String[] args){
char[] cc={'N','o','r','t','h','e','r','n',' ','C', 'a', 'l', 'i','f', 'o','r','n','i','a',' ','U','S','A'};
int start=cc.length-1;
for(int i=cc.length-1; i>=0; i--){
if(cc[i]==' ' || i==0)
{
for(int j=i; j<=start; j++){
System.out.print(cc[j]);
}
start=i;
}
}
}
public class SentenceReverse {
private static void printReverse(char[] chars){
int end = chars.length;
for(int i = chars.length - 1; i >= 0; i--){
if(i == 0 || chars[i-1] == ' '){
int k = i;
while(k < end){
System.out.print(chars[k]);
k++;
}
end = i;
System.out.print(" ");
}
}
}
public static void main(String[] args) {
printReverse("Northern California USA".toCharArray());
}
}
A> Reverse the whole string first.
B> Reverse individual words of the output string from step A.
- R@M3$H.N September 24, 2014