Avsa
BAN USERThis is quite easy. Just break down into cases to simplify
1. Take two variables of String smaller and biger
2. put small string between s1 and s2 in small and big in bigger
3. Now break down into sub cases
3.1 If smaller.size() == bigger.size()
{...} // Easy operation, see code below for inner details
3.2 If smaller.size()+1 == bigger.size()
{...} // Easy operation, see code below for inner details
3.3 return false;
public static boolean OneEditApart(String s1, String s2) {
int i = 0;
String small = s1.length() <= s2.length() ? s1 : s2;
String big = s1.length() > s2.length() ? s1 : s2;
if (small.length() == big.length()) {
while (i < small.length()) {
if (small.charAt(i) == big.charAt(i))
i++;
else
return small.substring(i + 1, small.length()).equals(
big.substring(i + 1, big.length()));
}
// Here both the Strings are same
return false;
} else if (small.length() + 1 == big.length()) {
while (i < small.length()) {
if (small.charAt(i) == big.charAt(i))
i++;
else
return small.substring(i, small.length()).equals(
big.substring(i + 1, big.length()));
}
return true;
} else
return false;
}
Very simple solution:
1. print all the left perimeter nodes except the leaf
2. print all the leaves in the tree
3. print all the right perimeter nodes except the leaf
Overall running time: O(n)+O(n)+O(n) = O(n)
void print_perimeter(Tree t)
{
if(t == null) return "";
Tree head = t;
// Print left perimeter except the leaf node
while(head.left != null)
{
print(head.value);
head = head.left;
}
// print all the leaves using help function left_print... see below
leaf_print(t);
//print all the right perimeter nodes in reverse manner except leaf node
head = t;
ArrayList<Tree> list = new ArrayList<Tree>();
while(head.right != null)
{
list.add(head.value);
head = head.left;
}
for(int i=list.size()-1; i>=0; i--)
print(list.get(i));
}
// help function to print leaves
void leaf_print(Tree t)
{
if(t.left == null && t.right == null)
{print(t.value)
return "";
}
if(t.left != null)
leaf_print(t.left);
if(t.right != null)
leaf_print(t.right);
}
1.Sort the given Array to make Array A
2.Add elements in new Array(B) in this order
(a)Take two iterators which points to beginning and end of Array A
(b)Fill B with element from beginning and then element from end
(c)increment beginning and decrement end
(d)Repeat step 2(b) until beginning < end
B is our required result(Elements in Alternative Order)
Running time: O(n log n)
So if the input Array is 3 5 7 8 4 9
Then A = 3 4 5 7 8 9
B = 3 9 4 8 5 7 which is our output
I got it, but i have one doubt. What about negative numbers. If you are making array of 256 index form 0 to 255. Byte[] A can have negative number also, so we do need to check before incrementing frequency of index?
- Avsa May 03, 2014What i mean, like if -25, then increment the frequency of count[127+25]?
Why i add 127; because positive numbers can atmost 127.
Please Advice.