java链表变成字符串,leetcode算法题解(Java版)-6-链表,字符串
一、字符串處理
題目描述
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路
把數字轉化為羅馬符號,根據羅馬符號的規律,可以先用map來存儲一下。之后把每一位添加到所求中去。
語法點:StringBuffer是字符緩沖區,是可以修改字符長度的,最后要用sb.toString()去返回緩沖區的字符串
代碼
//!COPY
public class Solution {
public String intToRoman(int num) {
String[][] map={
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"}
};
StringBuffer sb=new StringBuffer();
sb.append(map[3][num/1000%10]);
sb.append(map[2][num/100%10]);
sb.append(map[1][num/10%10]);
sb.append(map[0][num%10]);
return sb.toString();
}
}
二、鏈表
題目描述
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
思路
鏈表的題,雖然題目說存放的數字是反過來的,但是完全可以把加法也”反過來“,也就是說從”左到右“相加。
鏈表的題,一般都應該設置一個頭指針head(里面什么也不存放,只是用來記住鏈表的頭)
代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
ListNode head=new ListNode(0);
ListNode p=head;
int tem=0;
while(l1!=null||l2!=null||tem!=0){
if(l1!=null){
tem+=l1.val;
l1=l1.next;
}
if(l2!=null){
tem+=l2.val;
l2=l2.next;
}
p.next=new ListNode(tem%10);
p=p.next;
tem/=10;
}
return head.next;
}
}
三、最長無重復字符子串
題目描述
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
思路
水題漸漸做完了,開始碰到的題有難度了。這題用到了所謂的滑動窗口法:從左到右滑動,如果碰到了在左邊界內且出現過的字符,那就將左邊界移動到之前的那個字符的下一位,刷新求最大即可。
還看到一位大神的神解法,代碼很簡潔,思想其實也是一樣的:從左到右滑動,記錄每一個字符上一次出現的位置,在第i位時比較當前字符的上一次出現的位置和左邊界,刷新當前左邊界。
代碼1
import java.util.HashMap;
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap map=new HashMap<>();
int len=s.length();
if(s==null||len==0){
return 0;
}
int res=0;
int l=0;
for(int i=0;i
代碼2
import java.util.HashMap;
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMapmap=new HashMap<>();
int len = s.length();
if(s==null||len==0){
return 0;
}
for(int i=0;i
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java链表变成字符串,leetcode算法题解(Java版)-6-链表,字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为开学焕新季优惠 不论什么专业总有一款
- 下一篇: RedmiBook Pro 2022“芯