(算法题)Day-20230308
Excel 表列序号
从后往前 乘26
class Solution {
public int titleToNumber(String columnTitle) {
int len = columnTitle.length();
int num = 0;
int res=0;
for(int i=len-1;i>=0;i--){
int nofc = columnTitle.charAt(i)-'A'+1;
res += nofc*Math.pow(26,num);
num+=1;
}
return res;
}
}
Excel表列名称
细节很多!!!是A、B、C开始,相当于从1、2、3开始没有0,所以每次除 都得先减一!
一直除26,每次将余数 转为字符,注意最后需要进行翻转
class Solution {
public String convertToTitle(int columnNumber) {
StringBuilder sb = new StringBuilder();
while(columnNumber > 0){
columnNumber--;
sb.append((char)(columnNumber%26 + 'A'));
columnNumber/=26;
}
sb.reverse();
return sb.toString();
}
}
验证栈序列
模拟 入栈和出栈
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> stack = new ArrayDeque<Integer>();
int n = pushed.length;
for (int i = 0, j = 0; i < n; i++) {
stack.push(pushed[i]);
while (!stack.isEmpty() && stack.peek() == popped[j]) {
stack.pop();
j++;
}
}
return stack.isEmpty();
}
}
字典序排数
递归法
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> lexicalOrder(int n) {
for (int i = 1; i <= 9; i++) dfs(i, n);
return ans;
}
void dfs(int cur, int limit) {
if (cur > limit) return ;
ans.add(cur);
for (int i = 0; i <= 9; i++) dfs(cur * 10 + i, limit);
}
}
迭代法(代码非常优雅)
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> ans = new ArrayList<>();
for (int i = 0, j = 1; i < n; i++) {
ans.add(j);
if (j * 10 <= n) {
j *= 10;
} else {
while (j % 10 == 9 || j + 1 > n) j /= 10;
j++;
}
}
return ans;
}
}

浙公网安备 33010602011771号