009回文数
解析+代码 013罗马数字转整数
解析+代码 014最长公共前缀
解析+代码 020有效的括号
解析+代码 021合并两个有序链表
解析+代码
009回文数 解析+代码class Solution {
public boolean isPalindrome(int x) {
// 回文数,可以利用StringBuffer的reverse反转函数
// 将n转换为StringBuffer类型
StringBuffer s=new StringBuffer(String.valueOf(x));
return s.reverse().toString().equals(String.valueOf(x));
}
}
013罗马数字转整数
解析+代码
class Solution {
public int romanToInt(String s) {
// 记录整数
int num=0;
// 记录s的长度
int length=s.length();
// 求最后一个字符的罗马数字
char rear=s.charAt(length-1);
// 求最后一个字符的罗马数字对应的整数
switch(rear){
case 'I':
num=1;
break;
case 'V':
num=5;
break;
case 'X':
num=10;
break;
case 'L':
num=50;
break;
case 'C':
num=100;
break;
case 'D':
num=500;
break;
case 'M':
num=1000;
break;
}
// 字符串长度为1
if(s.length()==1){
return num;
}
// 字符串长度大于1
else{
// 记录当前遍历的罗马数字右边邻近的罗马数字对应的数字
int index1=num;
for(int i=length-2;i>=0;i--){
// 记录当前遍历的罗马数字
char front=s.charAt(i);
// 记录当前罗马数字对应得数字
int index2=0;
// 求罗马数字对应的数字
switch(front){
case 'I':
index2=1;
break;
case 'V':
index2=5;
break;
case 'X':
index2=10;
break;
case 'L':
index2=50;
break;
case 'C':
index2=100;
break;
case 'D':
index2=500;
break;
case 'M':
index2=1000;
break;
}
// 当前遍历的罗马数字小于右边邻近的数字时
if(index2
014最长公共前缀
解析+代码
class Solution {
public String longestCommonPrefix(String[] strs) {
int i=0,j=0;
// 第一个for循环:
// 遍历第一个字符串的字符
for( ;i0){
// 存在
return strs[0].substring(0,i);
}else{
// 不存在
return "";
}
}
}
020有效的括号
解析+代码
class Solution {
public boolean isValid(String s) {
// 考察知识点:栈
// 先判断字符串的长度,奇数一定不是有效的
// 记录字符串的长度
int length=s.length();
// 判断是否为奇数
if(length%2!=0){
// 奇数
return false;
}
else{
// 偶数
// 创建栈
// 注意要用包装类Character
Stackstack=new Stack();
// 遍历字符串
for(int i=0;i
021合并两个有序链表
解析+代码
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// 链表list1为空
if(list1==null&&list2!=null){
return list2;
}
// 链表list2为空
else if(list1!=null&&list2==null){
return list1;
}
// 两个链表都为空
else if(list1==null&&list2==null){
return null;
}
// 两个链表都不为空
else{
// 创建头结点
ListNode head=new ListNode();
ListNode node=head;
// 遍历链表list1,list2
while(list1!=null&&list2!=null){
// 当前遍历list1的结点的val较小或者两者相等
if(list1.val<=list2.val){
node.next=list1;
list1=list1.next;
node=node.next;
}
else{
node.next=list2;
list2=list2.next;
node=node.next;
}
}
// 当list1未遍历完
if(list1!=null){
node.next=list1;
}
// 当list2未遍历完
else if(list2!=null){
node.next=list2;
}
return head.next;
}
}
}



