Amazon Interview Question
Software Engineer / DevelopersJava Solution:
public class StringManiputlation {
public static void main(String args[]) throws IOException{
Map<String,Integer> m = new HashMap<String,Integer>();
int length = args.length;
for (int i=0;i<length;i++)
{
Integer freq = m.get(args[i]);
m.put(args[i],(freq==null)?1:freq++);
}
System.out.println("Distinct characters"+ m.size());
}
sorry corrected version:
public class StringManiputlation {
public static void main(String args[]) throws IOException{
Map<String,Integer> m = new HashMap<String,Integer>();
int length = args.length;
for (int i=0;i<length;i++)
{
Integer freq = m.get(args[i]);
m.put(args[i],(freq==null)?1:freq+1);
}
Iterator<String> it = m.keySet().iterator();
while(it.hasNext())
{
String key = it.next();
System.out.println(key + m.get(key));
}
}
}
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
map< char, int > charCount;
string s( "amazon.com" );
string::const_iterator end = s.end();
string::const_iterator i = s.begin();
for ( ; i != end; ++i )
if ( ( *i >= 'a' && *i <= 'z' ) || ( *i >= 'A' && *i <= 'Z' ) )
++charCount[ *i ];
map< char, int >::const_iterator end1 = charCount.end();
map< char, int >::const_iterator j = charCount.begin();
for ( ; j != end1; ++j )
cout << j->first << ", " << j->second << "\n";
return 0;
}
We can use a Hashtable with the alphabetsa as key and the objects intially to 0.
Now for every alphabet we see increment the count in the hash table and finally we end up having the counts...
public class count {
public static void main(String args[])
{
String str="amazon.com";
char[] ele=str.toCharArray();
Hashtable<Character, Integer> elements=new Hashtable<Character, Integer>();
for(int i=0;i<ele.length;i++)
elements.put(ele[i], 0);
for(int i=0;i<ele.length;i++)
{
elements.put(ele[i], (elements.get(ele[i])+1));
}
for(int i=0;i<ele.length;i++)
System.out.println(ele[i]+"count"+elements.get(ele[i]));
}
}
void printcount(int a[])
- TOPCODER March 22, 2010{
int i,b[256];
for(i=0;i<255;i++)
{
b[i]=0;
}
for(i=0;i<a.length;i++)
{
if(!b[a[i]])
{
b[a[i]]++;
}
else
{
printf("\n Element at index %d and its count is %d",a[i],b[a[i]]);
}
}
}