(1) 判断两个字符串是否互为循环表示。如“abcd”和“dabc”是互为循环表示,“body”和“dybo”也是互为循环表示。而“abcd”、“dcab”则不是。写一个方法,入参为两个字符串 word1,word2。如果两个字符串是循环表示,返回true;否则返回false。
public boolean isCircleString(String word1, String word2) {String temp = word1;int length = word1.length();for (int i = 0; i < length; i++) {temp = temp.substring(length - 1, length)+ temp.substring(0, length - 1);if (temp.equals(word2))return true;}return false;}
(2) 给定一个数组,元素都是正整数,要求返回这些元素组成的最大数。
例如:[6,82,7,2]则返回82762,[7,8,89,4]则返回89874
此题在LeetCode上有 /problems/largest-number/
public int getMaxNumber(int array[]) {List<String> list = new LinkedList<String>();for (int data : array) {list.add(data + "");}StringBuilder builder = new StringBuilder();while (list.size() > 0) {String temp = list.get(0);for (Iterator<String> it = list.iterator(); it.hasNext();) {String current = it.next();temp = compare(temp, current); // 调用比较方法}builder.append(temp);list.remove(temp);}return Integer.parseInt(builder.toString());}
public String compare(String str1, String str2) {int n1 = Integer.parseInt(str1 + str2);int n2 = Integer.parseInt(str2 + str1);return n1 > n2 ? str1 : str2;}