Interview Question
#include<iostream>
#include<string>
using namespace std;
char *arr[] = {"xxxB","yyyC","zzzA"};
void sort()
{
for(int i = 0; i < 3 ; i++)
{
for(int j = i+1; j < 3 ; j++)
{
if(strcmp(arr[i],arr[j])> 0)
{
char *temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void reverse(char *p,int len)
{
char arrev[strlen(p)];
int i = strlen(p)- 1;
int y = 0;
int j = len;
int count = strlen(p);
p = p + strlen(p)- 1;
while(i >=0)
{
arrev[y] = *p;
*p--;
i-- ;
y++;
}
arrev[count]= '\0';
strcpy(arr[j],arrev);
}
int main()
{
for (int i = 0; i < 3 ; i++)
{
reverse(arr[i],i);
}
sort();
for (int i = 0; i < 3 ; i++)
{
reverse(arr[i],i);
}
for (int i = 0; i < 3 ; i++)
{
cout<<"arr=="<<arr[i]<<endl;
}
return 0;
}
public static String reverse(String str){
StringBuilder sb = new StringBuilder();
for(int i=str.length()-1; i>=0; i--)
sb.append(str.charAt(i));
return sb.toString();
}
public static void main(String[] args) {
String[] arr = {"zzzC", "yyyB", "xxxA"};
HashMap<String, String> hm = new HashMap<String, String>();
for(int i=0; i< arr.length; i++){
hm.put(reverse(arr[i]),arr[i]);
}
ArrayList<String> tmp = new ArrayList<String>(hm.keySet());
Collections.sort(tmp);
ArrayList<String> result = new ArrayList<String>();
for(String str: tmp){
result.add(hm.get(str));
}
Object[] resultArr = result.toArray();
for (int i = 0; i < resultArr.length; i++)
System.out.println((String) resultArr[i]);
}
public static String reverse(String str){
StringBuilder sb = new StringBuilder();
for(int i=str.length()-1; i>=0; i--)
sb.append(str.charAt(i));
return sb.toString();
}
public static void main(String[] args) {
String[] arr = {"zzzC", "yyyB", "xxxA"};
HashMap<String, String> hm = new HashMap<String, String>();
for(int i=0; i< arr.length; i++){
hm.put(reverse(arr[i]),arr[i]);
}
ArrayList<String> tmp = new ArrayList<String>(hm.keySet());
Collections.sort(tmp);
ArrayList<String> result = new ArrayList<String>();
for(String str: tmp){
result.add(hm.get(str));
}
Object[] resultArr = result.toArray();
for (int i = 0; i < resultArr.length; i++)
System.out.println((String) resultArr[i]);
}
The best way to tackle these customized sorts is to provide a Comparator function (solution below is in Java. I guess in C++ also you can do this)
- Anonymous December 31, 2010So Comparator would be :
Comparator<String> reverseComparator = new Comparator<String>() {
public int compare(String s1, String s2) {
String rev1 = //reverse the first String s1 here;
String rev2 = //reverse the first String s2 here;
return rev1.compareTo(rev2);
}
};
List<String> originalStringList = Arrays.asList("xxxB", "yyyC", "zzzA");
Collections.sort(originalStringList, reverseComparator);