1、替换所有的问号 - 力扣(LeetCode)
思路:
- 首先找到需要替换的 ' ? ',位置
- 然后遍历26个字母与 '?' 的左右两边的是否相同,不同的话就替换
- 最后返回即可
- 代码:
public String modifyString(String s) {char[] ch = s.toCharArray();int n = s.length();for(int i = 0; i < n; i++){if(ch[i] == '?'){//替换for(char j = 'a'; j <= 'z'; j++){if(((i == 0) || (ch[i-1] != j)) && ((i == n-1) || (ch[i+1] != j))){ch[i] = j;break;}} }}return String.valueOf(ch);}
2、提莫攻击 - 力扣(LeetCode)
思路:
- 当差值小于中毒的持续时间时,那么中毒时间就是差值,大于中毒持续时间时, 那么时间就是d
- 代码:
public int findPoisonedDuration(int[] timeSeries, int duration) {int ret = 0;for(int i = 1; i < timeSeries.length; i++){int x = timeSeries[i] - timeSeries[i-1];if(x >= duration){ret += duration;}else{ret += x;}}return ret + duration;}
3、Z 字形变换 - 力扣(LeetCode)
思路:
- 双层循环遍历矩阵,然后填写数组
- 找规律,简化操作
public String convert(String s, int numRows) {//处理边界if(numRows == 1){return s;}int d = 2*numRows - 2;StringBuilder ret = new StringBuilder();//处理第一行for(int i = 0; i < s.length(); i += d){ret.append(s.charAt(i));}//处理中间行//依次枚举中间行for(int k = 1; k < numRows-1; k++){for(int i = k, j = d-i; i < s.length() || j < s.length(); i+=d, j+=d){if(i < s.length()){ret.append(s.charAt(i));}if(j < s.length()){ret.append(s.charAt(j));}}}//处理最后一行for(int i = numRows-1; i < s.length(); i+=d){ret.append(s.charAt(i));}return ret.toString();}
4、外观数列 - 力扣(LeetCode)
思路:
- 定义left和right两个指针从头开始
- 如果left位置的值等于right的话,right向右移动
- 直到不相等就统计一下,个数和值
- 代码:
public String countAndSay(int n) {String ret = "1";//解释n-1次 ret即可for(int i = 1; i < n; i++){int len = ret.length();StringBuilder tmp = new StringBuilder();for(int left = 0, right = 0; right < len; ){// 防止越界while(right < len && ret.charAt(right) == ret.charAt(left)){right++;}//组合一下结果tmp.append(Integer.toString(right - left));tmp.append(ret.charAt(left));left = right;}//内循环结束就赋值到最终结果上ret = tmp.toString();}return ret;}