Tuesday, September 27, 2016

Android Studio Project: Experiment Manager

Experiment Manager, focusing on biological research.

This application makes experiments arrangement as its main function, supplemented by columns such as biological information and data searching. What’s more, it can save your experiments experiences. With this application, you will be able to do every experiment more methodically. When not doing an experiment, you can either know about biological related news or seeking for the latest information from professional websites. How flexible and convenient!

Experiment Manager


Click To Download On Amazon Appstore

Project site

Thursday, September 22, 2016

Android Studio Project: Outside News Updated

The new version of Outside News repairs a bug that the application couldn't exit from MainActivity directly.

Installation package

Project site

Thursday, September 8, 2016

LeetCode Online Judge-10. Regular Expression Matching

Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

Tell you a secret. I initially added only 1 line and it was accepted!
Well, that's "return s.matches(p);" in Java. Ha-ha!

OK, I did know this answer was not expected for training.
So here comes my recursive program.

//Java Program: Regular Expression Matching
public class Solution {
    public boolean isMatch(String s, String p) {

if (p.length()==0) {
if (s.length()==0) {
return true;
} else {
return false;
}
}

if (p.length()==1) {
if (s.length()==1&&(p.charAt(0)=='.'||s.charAt(0)==p.charAt(0))) {
return true;
}
return false;
}

if (s.length()>0&&p.length()>0&&(p.charAt(p.length()-1)=='.'||s.charAt(s.length()-1)==p.charAt(p.length()-1))) {
return isMatch(s.substring(0, s.length()-1), p.substring(0, p.length()-1));
}

if (p.length()>1&&p.charAt(p.length()-1)=='*') {
if (s.length()==0) {
return isMatch(s, p.substring(0, p.length()-2));
}
if (p.charAt(p.length()-2)!='.'&&s.charAt(s.length()-1)!=p.charAt(p.length()-2)) {
return isMatch(s, p.substring(0, p.length()-2));
}
if (isMatch(s, p.substring(0, p.length()-2))) {
return true;
}
if (isMatch(s.substring(0, s.length()-1), p.substring(0, p.length()-2))) {
return true;
}
return isMatch(s.substring(0, s.length()-1), p);
}

return false;

    }
}

Friday, September 2, 2016

LeetCode Online Judge-9. Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
Acturally, I used extra space when solving this problem. But this answer was accepted. And I went to see the discussions about this problem. It seems impossible to solve the problem without extra space.
However, it's quite easy to solve this problem without the limit of extra space. Maybe there will be a perfect answer without extra space. Why not think about it?
OK, here comes my solution with extra space.

//Java Program: Palindrome Number
public class Solution {
    public boolean isPalindrome(int x) {
        String s = ((Integer)x).toString();
        for(int i=0;i<s.length()/2;++i) {
         if (s.charAt(i)!=s.charAt(s.length()-1-i)) {
         return false;
         }
        }
        return true;
    }
}



Thursday, September 1, 2016

LeetCode Online Judge-8. String to Integer (atoi)

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

//Java Program: String to Integer (atoi)
public class Solution {
    public int myAtoi(String str) {
        int i = 0;
while (i<str.length()&&str.charAt(i)==' ') {
++i;
}
if (i==str.length()) {
   return 0;
}
if (!((str.charAt(i)=='-'&&i<str.length()-1&&str.charAt(i+1)>='0'&&str.charAt(i+1)<='9')||(str.charAt(i)=='+'&&i<str.length()-1&&str.charAt(i+1)>='0'&&str.charAt(i+1)<='9')||(str.charAt(i)>='0'&&str.charAt(i)<='9'))) {
   return 0;
}
String s = str.substring(i);
int j;
for(j=1;j<s.length();++j) {
if (s.charAt(j)<'0'||s.charAt(j)>'9') {
break;
}
}
try {
return Integer.parseInt(s.substring(0, j));
} catch (NumberFormatException e) {
   if (str.charAt(i)=='-') {
       return Integer.MIN_VALUE;
   } else {
       return Integer.MAX_VALUE;
   }
}
    }
}

LeetCode Online Judge-7. Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

//Java Program: Reverse Integer
public class Solution {
    public int reverse(int x) {
        int flag = 1, temp = x;
    long r = 0;
    if (x<0) {
    flag = -1;
    temp = -x;
    }
    while (temp>0) {
    r = r*10 + temp%10;
        if (r>Integer.MAX_VALUE) {
        return 0;
        }
    temp /= 10;
    }
return flag*(int)r;
    }
}

LeetCode Online Judge-389. Find the Difference

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

//Java Program: Find the Difference
public class Solution {
    public char findTheDifference(String s, String t) {
        ArrayList<Character> alC = new ArrayList<Character>();
        for(int i=0;i<s.length();++i) {
            alC.add((Character)s.charAt(i));
        }
        for(int i=0;i<t.length();++i) {
        if (!alC.remove((Character)t.charAt(i))) {
                return t.charAt(i);
            }
        }
        return t.charAt(0);
    }
}

Tuesday, August 30, 2016

LeetCode Online Judge-6. ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

//Java Program: ZigZag Conversion
public class Solution {
    public String convert(String s, int numRows) {
        if (numRows==1) {
            return s;
        }
        char[] r = new char[s.length()];
char[][] c = new char[numRows][(s.length()/(2*numRows-2)+1)*(numRows-1)];
for(int i=0;i<s.length();++i) {
if (i%(2*numRows-2)<numRows) {
c[i%(2*numRows-2)][i/(2*numRows-2)*(numRows-1)] = s.charAt(i);
} else {
c[2*numRows-2-i%(2*numRows-2)][i/(2*numRows-2)*(numRows-1)+i%(2*numRows-2)-numRows+1] = s.charAt(i);
}
}
for(int k=0,i=0;i<c.length;++i) {
for(int j=0;j<c[0].length;++j) {
if (c[i][j]!='\u0000') {
r[k++] = c[i][j]; 
}
}
}
return String.valueOf(r);
    }
}

Android Studio Project: Classic Minesweeper Game Updated

The new version of Minesweeper repairs the problem that timing doesn't restart in some cases.

Click To Download On Amazon Appstore

Project site are in my previous post: Android Studio Project: Classic Minesweeper Game.

Friday, August 26, 2016

Android Studio Project: Classic Minesweeper Game

This is a game based on classic Minesweeper but not just that. It's a perfect reproduction of classic Windows Minesweeper game on Android. Have fun!

Click To Download On Amazon Appstore

Project site

Android Studio Project: Classic 2048 Game Updated

The new version of 2048 adds back button to make this game more flexible, and adds exit prompt to prevent muffed exits effectively. In the meantime, the problem of too many cards on some devices has been repaired.

Click To Download On Amazon Appstore

Project site are in my previous post: Android Project: Classic 2048 Game.

Tuesday, August 23, 2016

Android Learning Note: Being Cautious To Use static Modifier When Defining A Variable

Using static modifier when defining a variable in a class means it's a class variable, which has only 1 identical value in different instance objects.

Saturday, August 20, 2016

LeetCode Online Judge-5. Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

//Java Program: Longest Palindromic Substring
public class Solution {
    public String longestPalindrome(String s) {
        
        //In this program, there is no empty string acturally.
        if (s.length()==0) {
return null;
}

String result = s.substring(0, 1);

//Axis of symmetry: i/2.0
for(int i=1,j;i<2*s.length()-2&&(s.length()-1-i/2)*2+1>result.length();++i) {
for(j=0;(i-1)/2-j>=0&&i/2+1+j<s.length();++j) {
if (s.charAt((i-1)/2-j)!=s.charAt(i/2+1+j)) {
break;
}
}
String temp = s.substring((i-1)/2-j+1, i/2+1+j);
if (temp.length()>result.length()) {
result = temp;
}
}

return result;

    }

}

LeetCode Online Judge-4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

//Java Program: Median of Two Sorted Arrays
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.length == 0) {
switch(nums2.length % 2) {
case 0: 
return (nums2[nums2.length / 2 - 1] + nums2[nums2.length / 2]) / 2.0;
case 1:
return nums2[nums2.length / 2];
}
}
if (nums2.length == 0) {
switch(nums1.length % 2) {
case 0: 
return (nums1[nums1.length / 2 - 1] + nums1[nums1.length / 2]) / 2.0;
case 1:
return nums1[nums1.length / 2];
}
}
int[] array = new int[2];

int i = 0, j = 0;
while (i + j <= (nums1.length + nums2.length + 1) / 2) {

int next;

if (i < nums1.length && j < nums2.length) {
next = nums1[i] <= nums2[j] ? nums1[i++] : nums2[j++];
} else if (i == nums1.length) {
next = nums2[j++];
} else {
next = nums1[i++];
}

            if (i + j >= (nums1.length + nums2.length + 1) / 2) {
   array[i + j - (nums1.length + nums2.length + 1) / 2] = next;
            }

}

if ((nums1.length + nums2.length) % 2 == 0) {
return (array[0] + array[1]) / 2.0;
} else {
return array[0];
}
    }
    
}

Though this program is accepted, I think it's not very good.
Firstly, it can't deal with two empty arrays nums1 and nums2.
Secondly, the logic of this program is hard to understand, especially the loop condition. Acturally, I just want to make the element(s) of array to participate in final compution. If you, what the loop condition will be? After thinking, you may understand my program better. And next is to find next minimum number. Note that the second if sentence in the while loop is behind i++ or j++, so you need to be careful with the condition.
In fact, I have optimized this program a lot during writing this post, which indicates the importance of summary. If you have better solution and are glad to share, just post your comment and laugh at me.

LeetCode Online Judge-3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

//Java Program: Longest Substring Without Repeating Characters
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        int longestLength = 0;
ArrayList<Character> list = new ArrayList<Character>();
for(int i=0;i<s.length();++i) {
if (list.contains(s.charAt(i))) {
while(list.get(0)!=s.charAt(i)) {
list.remove(0);
}
list.remove(0);
}
list.add(s.charAt(i));
if (list.size() > longestLength) {
   longestLength = list.size();
}
}
return longestLength;
    }
}

Thursday, August 18, 2016

Java Program: To Reconstruct A Binary Tree

This program is to reconstruct a binary tree according to its preorder and inorder traversals.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if (pre==null)
             return null;
        TreeNode treeNode = new TreeNode(pre[0]);
        int i = 0;
        while (i<in.length&&in[i]!=pre[0])
            ++i;
        if (i>=in.length) {
        return null;
        }
        if (i>=1) {
        int[] preleft = new int[i];
        int[] inleft = new int[i];
        for(int j=0;j<i;++j) {
        preleft[j] = pre[j+1];
        inleft[j] = in[j];
        }
        treeNode.left = reConstructBinaryTree(preleft, inleft);
        } else {
        treeNode.left = null;
        }
        if (i<pre.length-1) {
       int[] preright = new int[pre.length-i-1];
       int[] inright = new int[pre.length-i-1];
       for(int j=0;j<pre.length-i-1;++j) {
           preright[j] = pre[i+j+1];
           inright[j] = in[i+j+1];
       }
       treeNode.right = reConstructBinaryTree(preright, inright);
        } else {
        treeNode.right = null;
        }
        return treeNode;
    }
}

Wednesday, August 17, 2016

Java Program: Replace Space With "%20" In A String

Here is a java program to replace space with "%20" in a string. For example, the string "We Are Happy" will be changed to "We%20Are%20Happy".
Note that a space is a character while "%20" is a string.

//Replace Space With "%20" In A String
public class Solution {
    public String replaceSpace(StringBuffer str) {
     StringBuffer s = new StringBuffer();
 
  for(int i=0;i<str.length();++i) {
   if (str.charAt(i)==' ') {
    s.append("%20");
   } else {
    s.append(str.charAt(i));
   }
  }
        return s.toString();
    }
}

Monday, August 8, 2016

Android Studio Project: Outside News

The previous projects I have made are mainly about logical thinking. Today, I share this project, Outside News to all of you, which is full of beautiful user interfaces. I'm sorry that it's only a demo without news recources and strong features. If you want to have a try, just do it!

Installation package

Project site

Is this project with the use of Viewpager, ListView, PopupWindow, PopupMenu and many other views more colorful? What's more, it uses SharedPreferences and SQLite database to store some data persistently. And it involves multithread programming and asynchronous message processing. The use of vector is also one of my harvests.

Sunday, August 7, 2016

Android Learning Note: To Set The Color Of Cursor The Same As Text Color In An EditText

To set the color of cursor the same as text color in an EditText, just add a sentence in the layout file like this:

 android:textCursorDrawable="@null"

"@null" here means the color of cursor is the same with the text. It's said that you can change it as you like to set the color arbitrarily. You may have a try.

Android Learning Note: To Delete The Default Bottom Line Of EditText

To delete the default bottom line of EditText, just add the following sentence in the layout file, of course, between "<EditText" and "/>".

android:background="@null"

Friday, August 5, 2016

Android Learning Note: Never Set 2 Different Layout To 1 Activity

This is the original post of mine, which is wrong in fact.



Just add the following codes behind "super.onCreate(savedInstanceState);" sentence in the onCreate(Bundle savedInstanceState) methed of the main Activity.


//Entering Splash Screen. Here I use the layout file welcome.xml
setContentView(R.layout.welcome);

// Creating a Handler object and operate it like this. You may set another waiting time
new Handler() {
    @Override    public void handleMessage(Message msg) {
        setContentView(R.layout.activity_main);
    }
}.sendEmptyMessageDelayed(1,2000);

After short enjoyness, I got into trouble caused by the codes below. Crap say no more, I used the methed setContentView() twice in the codes below, which caused serious NullPointerException in the following codes.
Maybe this is a stupid mistake for many of you, I thgink it valuable for me, for I have debuged the program and resulted others to make sense of it. And I'm impressed on this error, believing that I'll never make this kind of mistake.

Never Set 2 Different Layout To 1 Activity.

Wednesday, August 3, 2016

Android Studio Project: Classic 2048 Game

Classic 2048 Game on Android. Just enjoy it!

Click To Download On Amazon Appstore

Project site

Android Studio Project: Calculator

This is an arithmetic calculator with brackets on Android.

It transforms the inputted infix expression to a postfix expression firstly, then computes the value of this postfix expression. Yeah, it is based on the thought of stack, an important kind of data structure. And the main layout of "Calculator" is "GridLayout".

Though it seems very simple, I learned a lot durng development.

A lightweight calculator on Android. Why not have a try?

Installation package

Project site

Tuesday, May 10, 2016

LeetCode Online Judge-2. Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

//C Program: Add Two Numbers
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int val;
    struct ListNode* q = l1;
    struct ListNode* p;
    while (l1&&l2)
    {
        p = l1;
        val = l1->val + l2->val;
        l1->val = val % 10;
        if (val >= 10)
        {
            if (!l1->next)
            {
                l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
                l1->next->val = 0;
                l1->next->next = NULL;
                if (!l2->next)
                {
                    l2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
                    l2->next->val = 0;
                    l2->next->next = NULL;
                }
            }
            l1->next->val += 1;
        }
        l1 = l1->next;
        l2 = l2->next;
    }
    while (l1&&l1->val>=10)
    {
        l1->val %= 10;
        if (!l1->next)
        {
            l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
            l1->next->val = 1;
            l1->next->next = NULL;
            break;
        }
        l1->next->val += 1;
        l1 = l1->next;
    }
    if (l2)
    {
        p->next = l2;
    }
    return q;
}

Monday, May 9, 2016

C Program: Isomorphism of Trees

Isomorphism of Trees


Given two trees T1 and T2. If T1 can become the same as T2 through swapping left and right children several times, then we consider these two trees are "isomorphic". For example, Figure 1 shows two isomorphic trees. If we swap the left and right children of nodes A, B, G of either tree, we can get another tree. But in Figure 2, the trees are not isomorphic.
Figure 1

Figure 2
Now given two trees, please determine whether they are isomorphic.

Input Specification:

Enter the information of 2 binary tree. For each tree, give a non-negative integer N(10) in the first line, which is the number of the tree nodes(the nodes are numbered from 0 to N - 1). Then N lines follewed, the ith line is related to No.i node, giving a capital letter in English stored in this node, the serial number of the left child node, and that of the right child node. If a child node is empty, give a "-" in the corresponding position. Every two given data should be separated with a space. Note: this question make sure that letters stored in all nodes are different from each other.

Output Specification:

If the two trees are isomorphic, print "Yes". Otherwise, print "No".

Sample Input 1 (Figure 1):

8
A 1 2
B 3 4
C 5 -
D - -
E 6 -
G 7 -
F - -
H - -
8
G - 4
B 7 6
F - -
A 5 1
H - -
C 0 -
D - -
E 2 -

Sample Output 1:

Yes

Sample Input 2 (Figure 2):

8
B 5 7
F - -
A 0 3
C 6 -
H - -
D - -
G 4 -
E 1 -
8
D 6 -
B 5 -
E - -
H - -
C 0 2
G - 3
F - -
A 1 4

Sample Output 2:

No
 
My program is following.
 
//Isomorphism of Trees

#include <stdio.h>
#include <stdlib.h>

//Tree node and pointer
typedef struct TreeNode
{
    char data;
    int left;
    int right;
} TreeNode, *Tree;

Tree tree1, tree2;//Two trees
Tree BuildTree(Tree* tree);
int Isomorphic(Tree p1, Tree p2);

int main(void)
{
    Tree T1, T2;
    T1 = BuildTree(&tree1);
    T2 = BuildTree(&tree2);
    if (Isomorphic(T1, T2))
    {
        printf("Yes\n");
    }
    else
    {
        printf("No\n");
    }
    return 0;
}

//To build a binary tree
Tree BuildTree(Tree* tree)
{
    int i, N;
    char leftc, rightc;
    scanf("%d", &N);
    getchar();
    *tree = (Tree)malloc(N * sizeof(TreeNode));//Expressing a binary tree through an array of structures
    if (N == 0)
    {
        return NULL;//Empty tree
    }
    int* flag = (int*)malloc(N * sizeof(int));
    for (i = 0; i < N; ++i)
    {
        flag[i] = 1;
    }
    for (i = 0; i < N; ++i)
    {
        scanf("%c %c %c", &((*tree + i)->data), &leftc, &rightc);//Input node information by characters
        getchar();
        if (leftc >= '0'&&leftc <= '9')
        {
            (*tree + i)->left = leftc - '0';//Having left child, transform the character to subscript of left child
            flag[(*tree + i)->left] = 0;
        }
        else
        {
            (*tree + i)->left = -1;//No left child, set it to -1
        }
        if (rightc >= '0'&&rightc <= '9')
        {
            (*tree + i)->right = rightc - '0';//Having right child, transform the character to subscript of right child
            flag[(*tree + i)->right] = 0;
        }
        else
        {
            (*tree + i)->right = -1;//No right child, set it to -1
        }
    }
    for (i = 0; i < N; ++i)
    {
        if (flag[i])
        {
            return *tree + i;
        }
    }
}

//To judge whether two trees are isomorphic
int Isomorphic(Tree p1, Tree p2)
{
    if (p1<tree1&&p2<tree2)//Both p1 and p2 are empty
    {
        return 1;
    }
    if ((p1<tree1&&p2>=tree2)||(p1>=tree1&&p2<tree2))//one of p1 and p2 is empty, another is not empty
    {
        return 0;
    }

    //Both p1 and p2 are not empty
    if (p1->data != p2->data)//Root node elements not equal
    {
        return 0;
    }
    return Isomorphic(tree1 + p1->left, tree2 + p2->left) && Isomorphic(tree1 + p1->right, tree2 + p2->right) || Isomorphic(tree1 + p1->left, tree2 + p2->right) && (Isomorphic(tree1 + p1->right, tree2 + p2->left));
}