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.
思路
把數(shù)字轉(zhuǎn)化為羅馬符號(hào),根據(jù)羅馬符號(hào)的規(guī)律,可以先用map來(lái)存儲(chǔ)一下。之后把每一位添加到所求中去。
語(yǔ)法點(diǎn):StringBuffer是字符緩沖區(qū),是可以修改字符長(zhǎng)度的,最后要用sb.toString()去返回緩沖區(qū)的字符串
代碼
//!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
思路
鏈表的題,雖然題目說(shuō)存放的數(shù)字是反過(guò)來(lái)的,但是完全可以把加法也”反過(guò)來(lái)“,也就是說(shuō)從”左到右“相加。
鏈表的題,一般都應(yīng)該設(shè)置一個(gè)頭指針head(里面什么也不存放,只是用來(lái)記住鏈表的頭)
代碼
/**
* 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;
}
}
三、最長(zhǎng)無(wú)重復(fù)字符子串
題目描述
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.
思路
水題漸漸做完了,開始碰到的題有難度了。這題用到了所謂的滑動(dòng)窗口法:從左到右滑動(dòng),如果碰到了在左邊界內(nèi)且出現(xiàn)過(guò)的字符,那就將左邊界移動(dòng)到之前的那個(gè)字符的下一位,刷新求最大即可。
還看到一位大神的神解法,代碼很簡(jiǎn)潔,思想其實(shí)也是一樣的:從左到右滑動(dòng),記錄每一個(gè)字符上一次出現(xiàn)的位置,在第i位時(shí)比較當(dāng)前字符的上一次出現(xiàn)的位置和左邊界,刷新當(dāng)前左邊界。
代碼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
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的java链表变成字符串,leetcode算法题解(Java版)-6-链表,字符串的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为开学焕新季优惠 不论什么专业总有一款
- 下一篇: java script 添加控件,【更新