Anonymous
BAN USERpublic void adjustPageWidth(String s, int pageWidth){
if(s.length()>1){
String [] words = s.split("\\s");
int space = words.length-1;
int totalSpace = space+(pageWidth-s.length());
space = totalSpace/(words.length-1);
int xtraSpace = totalSpace%(words.length-1);
StringBuffer str = new StringBuffer();
if(s.length()==pageWidth){
System.out.println("sentence already adjusted");
}
else{
for(int i =0;i<words.length;i++){
int temp = space;
str.append(words[i]);
while(temp>0){
str.append(" ");
temp--;
}
if(xtraSpace>0){
str.append(" ");
xtraSpace--;
}
}
}
System.out.println(str);
}
System.out.println("orginal string-->" + s);
}
This should work for strings with length>1. The algorithm inserts the spaces in between the words. But here the complexity is not O(n).
- Anonymous August 28, 2012public void interleaveStrings(String s1,String s2, String s3){
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
int count =0;
map = populateHashMap(s1,map);
map = populateHashMap(s2, map);
for(int i =0;i<s3.length();i++){
if(map!=null && map.containsKey(s3.charAt(i))){
if(map.get(s3.charAt(i))>1){
int val = map.get(s3.charAt(i));
map.put(s3.charAt(i), val-1);
count++;
}
else {
map.remove(s3.charAt(i));
count++;
}
}
}
if(count==(s1.length()+s2.length())){
System.out.println("strings are interleaved");
}
else{
System.out.println("strings are not interleaved");
}
}
public HashMap<Character,Integer> populateHashMap(String s, HashMap<Character,Integer> map){
for(int i = 0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){
int value = map.get(s.charAt(i));
map.put(s.charAt(i), value+1);
}
else{
map.put(s.charAt(i), 1);
}
}
return map;
}
I think this should run in complexity =O(3n)~ O(n). But then it will i think depend on the length of the string how does this constant factor matters. Please suggest if it does not work for any test string.
- Anonymous August 28, 2012
how will you check the depth of the tree just with the preorder traversal ??
- Anonymous August 30, 2012