1.问题
A cell (r, c) of an excel sheet is represented as a string “” where:
denotes the column number c of the cell. It is represented by alphabetical letters. For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on. is the row number r of the cell. The rth row is represented by the integer r. You are given a string s in the format ":", where represents the column c1, represents the row r1, represents the column c2, and represents the row r2, such that r1 <= r2 and c1 <= c2.Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
Example 1:
Input: s = “K1:L2”
Output: [“K1”,“K2”,“L1”,“L2”]
Explanation:
The above diagram shows the cells which should be present in the list.
The red arrows denote the order in which the cells should be presented.
Example 2:
Input: s = “A1:F1”
Output: [“A1”,“B1”,“C1”,“D1”,“E1”,“F1”]
Explanation:
The above diagram shows the cells which should be present in the list.
The red arrow denotes the order in which the cells should be presented.
Constraints:
- s.length == 5
- ‘A’ <= s[0] <= s[3] <= ‘Z’
- ‘1’ <= s[1] <= s[4] <= ‘9’
- s consists of uppercase English letters, digits and ‘:’.
2.解题思路
方法1和方法2
方法1和方法2的解题思路大体相同
1.新建一个list,为result
2.s中根据“:”数据分割成String的数组
3.String的数组d 的1个元素
4.String字符串l的第1个元素:字母
5.String字符串l的第2个元素 :数字
6.遍历元素,从字母l1到r1
7.遍历元素,从数字l2到r2
8.转换成String格式并添加到list中
3.代码
代码1
class Solution {
public List<String> cellsInRange(String s) {
List<String> result = new ArrayList<>();//1.新建一个list,为result
char l1 =s.charAt(0);//2.String字符串s的第1个元素:字母
char l2 =s.charAt(1);//3.String字符串s的第2个元素 :数字
char r1=s.charAt(3);//String字符串s的第1个元素: 字母
char r2 =s.charAt(4);//String字符串s的第2个元素:数字
for(char i = l1;i<=r1;++i) {//4.遍历元素,从字母l1到r1
for (char j = l2; j <= r2; j++) {//5.遍历元素,从数字l2到r2
result.add(String.valueOf(i) +j);//6.转换成String格式并添加到list中
//result.add(i + "" + j);使用char转为Stringl类型
//result.add(Character.toString(i) + Character.toString(j));
//result.add(new String(new char[]{i, j}));
}
}
return result;//返回result
}
}
代码2
public List<String> cellsInRange(String s) {
char c1 = s.charAt(0), c2 = s.charAt(3);
char r1 = s.charAt(1), r2 = s.charAt(4);
List<String> result = new ArrayList<>();
for (char c = c1; c <= c2; ++c) {
for (char r = r1; r <= r2; ++r) {//for (char r = r1; r <= r2; r++)
result.add("" + c + r);//result.add(Character.toString(i) + Character.toString(j));
}
}
return result;
}
class Solution {
public List<String> cellsInRange(String s) {
List<String> ans = new ArrayList<String>();
for(char i = 'A' ; i <= 'Z'; ++i) {
for(char j = '1'; j <= '9'; ++j) {
if(i >= s.charAt(0) && i <= s.charAt(3) && j >= s.charAt(1) && j <= s.charAt(4)){
ans.add(Character.toString(i) + Character.toString(j));
}
}
}
return ans;
}
}