剑指Offer之Java算法习题精讲数组与列表的查找及字符串转换
题目一
解法
class Solution { public String toLowerCase(String s) { StringBuilder sb = new StringBuilder(); for(int i = 0;i<s.length();i++){ char ch = s.charAt(i); if('A'<=ch&&ch<='Z'){ ch = (char)(ch+32); } sb.append(ch); } return sb.toString(); } }
题目二
解法
class Solution { public int pivotIndex(int[] nums) { int sum = 0; for(int i = 0;i<nums.length;i++){ sum+=nums[i]; } int left = 0; int right = sum; for(int i = 0;i<nums.length;i++){ right = right-nums[i]; if(i == 0){ left = 0; if(right==left) return 0; }else{ left+=nums[i-1]; if(right==left){ return i; } } } return -1; } }
题目三
解法
class Solution { public List<Integer> selfDividingNumbers(int left, int right) { ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = left;i<=right;i++){ if(selfDividing) list.add(i); } return list; } public boolean selfDividing(int n) { for (char c: String.valueOf(n).toCharArray()) { if (c == '0' || (n % (c - '0') > 0)) return false; } return true; } }
题目四
解法
class Solution { public char nextGreatestLetter(char[] letters, char target) { int left = 0; int right = letters.length; while(left<right){ int mid = left+(right-left)/2; if(letters[mid]<=target){ left = mid+1; }else{ right = mid; } } return left==letters.length?letters[0]:letters[left]; } }
到此这篇关于剑指Offer之Java算法习题精讲数组与列表的查找及字符串转换的文章就介绍到这了,更多相关Java 数组的查找内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)