题目:将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。(参考题解,需要再看)
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
题目链接:6. N 字形变换
时间复杂度(O(n))
解题思路:先填后读
class Solution {public String convert(String s, int numRows) {if(numRows < 2) return s;List<StringBuilder> rows = new ArrayList<StringBuilder>();for(int i = 0; i < numRows; i++) rows.add(new StringBuilder());int i = 0, flag = -1;for(char c : s.toCharArray()) {rows.get(i).append(c);if(i == 0 || i == numRows -1) flag = - flag;i += flag;}StringBuilder res = new StringBuilder();for(StringBuilder row : rows) res.append(row);return res.toString();}
}
无需再看
题目: 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给你一个整数,将其转为罗马数字。
题目链接: 12. 整数转罗马数字
**思路:**模拟即可
class Solution {public String intToRoman(int num) {int chushu=10;String result="";while(num>0){int oneofnumber=num%chushu;System.out.println(oneofnumber);num=num-oneofnumber;if(chushu==10){if(oneofnumber==0){result=result;}if(0<oneofnumber&&oneofnumber<4){while(oneofnumber>0){result="I"+result;oneofnumber=oneofnumber-1;}}if(oneofnumber==4){result="IV"+result;}if(4<oneofnumber&&oneofnumber<9){while(oneofnumber-5>0){result="I"+result;System.out.println("ok");oneofnumber=oneofnumber-1;}result="V"+result;}if(oneofnumber==9){result="IX"+result;}chushu=chushu*10;continue;}if(chushu==100){if(oneofnumber==0){result=result;}if(0<oneofnumber&&oneofnumber<40){while(oneofnumber>0){result="X"+result;oneofnumber=oneofnumber-10;}}if(oneofnumber==40){result="XL"+result;}if(40<oneofnumber&&oneofnumber<90){while(oneofnumber-50>0){result="X"+result;oneofnumber=oneofnumber-10;}result="L"+result;}if(oneofnumber==90){result="XC"+result;}chushu=chushu*10;continue;}if(chushu==1000){if(oneofnumber==0){result=result;}if(0<oneofnumber&&oneofnumber<400){while(oneofnumber>0){result="C"+result;oneofnumber=oneofnumber-100;}}if(oneofnumber==400){result="CD"+result;}if(400<oneofnumber&&oneofnumber<900){while(oneofnumber-500>0){result="C"+result;oneofnumber=oneofnumber-100;}result="D"+result;}if(oneofnumber==900){result="CM"+result;}chushu=chushu*10;continue;}if(chushu==10000){if(oneofnumber==0){result=result;}if(oneofnumber==1000){return "M"+result;}if(oneofnumber==2000){return "MM"+result;}if(oneofnumber==3000){return "MMM"+result;}chushu=chushu*10;continue;}}return result;}
}