Google Interview Question
Software Engineer / DevelopersTeam: codeblock
Country: India
Could you use #include<string> ?
class String{
private:
string m_data;
public:
String()
{
cout << "insert string: ";
getline(cin, m_data);
cout << endl;
}
void CheckIfPalindrome()
{
string revSentence = "";
string word = "";
for ( int i = 0; i < m_data.size(); ++i) {
word += m_data[i];
if ( m_data[i] == ' ') {
revSentence = word + revSentence;
word = "";
}
}
//last word
revSentence = word + " " + revSentence;
cout << revSentence << endl;
}
};
Java implementation...
public class ReverseSentance {
String orgStr="";
String revStr="";
/**
* @param args
*/
public ReverseSentance(String[] inStr)
{
for(String s: inStr)
orgStr=orgStr+s+" ";
orgStr=orgStr.substring(0, orgStr.length()-1);
int len = inStr.length;
for(int i = len-1; i>=0; i--)
{
revStr= revStr+inStr[i]+" ";
}
revStr=revStr.substring(0, revStr.length()-1);
}
public boolean checkForPalendrome()
{
boolean flag = true;
int i=0;
for(i=0;i < orgStr.length(); i++)
{
if(orgStr.charAt(i) != revStr.charAt(i))
break;
}
if(i==orgStr.length())
return true;
else
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] a = {"wife", "loves", "husband",",", "husband", "loves", "wife"};
ReverseSentance reverseObj = new ReverseSentance(a);
System.out.println(reverseObj.revStr);
if(reverseObj.checkForPalendrome())
{
System.out.println("it's Palendrome.. :)");
}else{
System.out.println("it's Not palendrome.. :( ");
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Example1 {
public static void main(String[] args) {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String sentence = br.readLine();
String[] words = sentence.split(" ");
for(int i=0;i<words.length/2;i++)
{
String temp= words[i];
words[i]=words[words.length-1-i];
words[words.length-1-i]=temp;
}
String s="";
for(int j=0;j<words.length;j++)
{
if(j==words.length-1)
s=s+words[j];
else
s=s+words[j]+" ";
}
System.out.println(s);
if(s.equals(sentence))
System.out.println("Yes Pallingdrome");
else
System.out.println("No Pallingdrome");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class String:
def __init__(self, sentence):
nospaces = ' '.join(sentence.split())
self.words = nospaces.split(' ')
def palindromecheck(self):
if not self.words:
return True
indexInit = 0
indexEnd = len(self.words) - 1
while indexInit <= indexEnd:
if self.words[indexInit] != self.words[indexEnd]:
return False
indexInit += 1
indexEnd -= 1
return True
Class only for the specified problem.
- Noobie October 28, 2012