</pre><pre name="code" class="java"></pre>6.ZigZag Conversion <p></p><p></p><p></p><pre name="code" class="java">package leetcode;
public class convert {
public String convert(String s, int nRows) {
if (s == null || s.length() == 0)
return "";
if (nRows <= 0)
return "";
if (nRows == 1)
return s;
int len = s.length();
StringBuilder sbd = new StringBuilder();
int step = 2 * nRows - 2;
for (int i = 0; i < nRows; i++) {
for (int j = i; j < len; j += step) {
sbd.append(s.charAt(j));
// 抛出最高和最低
if (i != 0 && i != nRows - 1) {
int temp = j + step - 2 * i;
if (temp < len)
sbd.append(s.charAt(temp));
}
}
}
return sbd.toString();
}
}
7.Reverse Integer
package leetcode;
public class reverse {
public int reverse(int x) {
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
long result = 0;
while (x != 0) {
int temp = x % 10;
result = result * 10 + temp;
if (result > max || result < min) {
return 0;
}
x = x / 10;
}
return (int) result;
}
}
8.String to Integer (atoi)
package leetcode;
public class myAtoi {
public int myAtoi(String str) {
if (str == null || str.length() < 1)
return 0;
str = str.trim();
int len = str.length();
String newstr = "";
boolean flag = false;
if (str.charAt(0) == '-') {
newstr = str.substring(0, len);
flag = true;
} else if (str.charAt(0) == '+') {
newstr = str.substring(0, len);
} else
newstr = str;
// 一定要用double类型
double result = 0;
int i = 0;
while (i < newstr.length() && newstr.charAt(i) >= '0' && newstr.charAt(i) <= '9') {
result = result * 10 + (newstr.charAt(i) - '0');
i++;
}
if (flag == true)
result = -result;
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
}
}
9.Palindrome Number
package leetcode;
public class isPalindrome {
public boolean isPalindrome(int x) {
int temp = x;
int result = 0;
if (x < 0)
return false;
while (temp > 0) {
result = result * 10 + temp % 10;
temp = temp / 10;
}
return x == result;
}
}
10.Regular Expression Matching
package leetcode;
public class isMatch {
public boolean isMatch(String s, String p) {
if (p.length() == 0) {
return s.length() == 0;
}
if (p.length() == 1) {
if (s.length() < 1) {
return false;
} else if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.')) {
return false;
} else {
return isMatch(s.substring(1), p.substring(1));
}
}
if (p.charAt(1) != '*') {
if (s.length() < 1) {
return false;
}
if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.')) {
return false;
} else {
return isMatch(s.substring(1), p.substring(1));
}
}
// p.charAt(1) == '*'
else {
if (isMatch(s, p.substring(2))) {
return true;
}
int i = 0;
while (i < s.length() && (s.charAt(i) == p.charAt(0) || p.charAt(0) == '.')) {
if (isMatch(s.substring(i + 1), p.substring(2))) {
return true;
}
i++;
}
return false;
}
}
}