题目1:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
import java.util.ArrayList;
import java.util.List;
public class ValidPalindrome {
public boolean isPalindrome(String s){
if(s == null || s.trim().equals("")){
return true;
}
List<Character> list = new ArrayList<Character>();
s = s.toLowerCase();
for(int i = 0; i < s.length(); i ++){
if(Character.isLetterOrDigit(s.charAt(i))){
list.add(s.charAt(i));
}
}
for(int i = 0, j = list.size() - 1; i < j; i ++, j --){
if(list.get(i) != list.get(j)){
return false;
}
}
return true;
}
public static void main(String[] args) {
String s = "A man, a plan, a canal: Panama";
ValidPalindrome v = new ValidPalindrome();
System.out.println(v.isPalindrome(s));
}
}
题目2:
Remove Duplicates From Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
源代码:
public class RemoveDuplicatesFromSortedArray {
public static int removeDuplicates(int[] A) {
if(A == null|| A.length <= 0){
return 0;
}
int i = 0, j = 1;
int len = A.length;
while(j < len){
if(A[i] < A[j]){
A[++ i] = A[j];
}
j ++;
}
return i + 1;
}
public static void main(String[] args) {
int[] A = {};
int len = RemoveDuplicatesFromSortedArray.removeDuplicates(A);
for(int i = 0; i < len; i ++){
System.out.print(A[i] + " ");
}
}
}
3.Pascal's Triangle
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
代码:
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
int row = 1;
while(row <= numRows){
<span style="white-space:pre"> </span>List<Integer> sub = new ArrayList<Integer>();
<span style="white-space:pre"> </span>sub.add(1);
<span style="white-space:pre"> </span>if(row != 1){
<span style="white-space:pre"> </span>List<Integer> preList = list.get(row - 2);
<span style="white-space:pre"> </span>for(int i = 0; i < preList.size() - 1; i ++){
<span style="white-space:pre"> </span>sub.add(preList.get(i) + preList.get(i + 1));
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>sub.add(1);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>row ++;
<span style="white-space:pre"> </span>list.add(sub);
}
return list;
}
}