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: 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