百度知道里看到这个题目的,网上有JAVA的代码,试着用python重写了一遍。python编程 求最大的‘镜子’组 比如{1, 2, 3, 8, 9, 3, 2, 1} 是 3 ( {1, 2, 3} 部分). return最大数。以下是网上找到的java代码。- public int maxMirror(int[] nums) {
- int[] reverse = null;
- int max = 0;
- for(int i = 0; i < nums.length; i++) {
- for(int k = 0; k < nums.length; k++) {
- if(i > k) {
- } else {
- reverse = reverseSection(nums, i, k);
- if(searchFor(reverse, nums)) {
- if(reverse.length > max) { max = reverse.length; }
- }
- }
- }
- }
-
- return max;
- }
- public int[] reverseSection(int[] nums, int begin, int end) {
- int[] nArray = new int[end - begin + 1];
- int numbs = end - begin;
- for(int i = begin; i <= end; i++) {
- nArray[numbs] = nums[i];
- numbs--;
- }
- return nArray;
- }
- public boolean searchFor(int[] reverse, int[] nums) {
- int index = 0;
- boolean check = false;
- for(int i = 0; i < nums.length; i++) {
- if(nums[i] == reverse[index]) {
- index++;
- if(index >= reverse.length) {
- return true;
- }
- } else {
- index = 0;
- }
- }
- return false;
乍一看,觉得问题很复杂,水平有限,代码量可能比较多,自己一个人不太可能在短时间内完成,没想到代码竟然这么短,六行代码就搞定了,py的确很强大。
- def maxmirror(a):
- b = [a[i:i+j] for j in range(len(a),0,-1) for i in range(len(a)-j+1)]
- for i in b:
- if list(reversed(i)) in b:
- return len(i)
- return 0
- if __name__ == '__main__':
- b = [[21,22,9,8,7,6,23,24,6,7,8,9,25,7,8,9],[1,2,1,20,21,1,2,1,2,23,24,2,1,2,1,25],[1,2,3,2,1],[1,2,3,3,8],[1,2,7,8,1,7,2],[1,1,1],[1],[],[9,1,1,4,2,1,1,1]]
- for a in b:
- print(a,'→', maxmirror(a))
阅读(1949) | 评论(0) | 转发(0) |