算法小题(一):按字典排序的子字符串

用友2018秋招算法小题

原题目:

/**
 * 找出连续数字字串的[开始元素,连续个数]
 * 样例:
 * input:    8 3 4 5 6 9 12 16【一行输入,按空格分隔】
 * output:  [3,4]
 */

注意:遍历下一个元素时,数组越界问题

public class Main {
	public static void main(String[] args){
		Scanner sc =new Scanner(System.in);
		String str[] = sc.nextLine().split(" ");
		int nums[] = new int[str.length];
		// 放入整型数组
		for(int i=0; i<str.length; i++){
			nums[i] = Integer.parseInt(String.valueOf(str[i]));
//			System.out.println(str[i]);
		}
		
		getResult(nums);	
	}
	
	static public void getResult(int num[]){
		int start= 0;	// 连续数字的开始下标
		int max = 0;    // 记录连续数字的最大个数
		int temp= 0 ;	// temp加载每个数组元素
		int next= 0;	// temp的下一个元素
		int count = 1; 	
		
		for(int i = 1; i <num.length; i++){	// i为下标,遍历数组,注意数组不能越界
			temp = num[i-1];	
			next = num[i];
			if((next-temp) == 1){
				count ++;
			}else{
				if(max < count){
					max = count;
					start = i - count;
				}
//				count = 1;
			}
		}
		max = max>count? max:count;
		for(int i = start; i<start+max; i++){
			System.out.print(num[i]+" ");
		}
		System.out.println("["+num[start]+","+count+"]");
	}
	
}

input:8 3 4 5 6 9 12 16

输出结果为:

========================= =================================================

若题目改成——找出按字典排序的字串:

/**
 * 找出按字典排序数字最大字串的[开始元素,连续个数]
 * 样例:
 * input:    1 3 4 5 6 9 12 16 10 18
 * output:  [1,8]
 */

package Yonyou;

import java.util.Scanner;
/**
 * 找出按字典排序数字最大字串的[开始元素,连续个数]
 * 样例:
 * input:	1 3 4 5 6 9 12 16 10 18
 * output:  [1,8]
 */
public class Main2 {
	public static void main(String[] args){
		Scanner sc =new Scanner(System.in);
		String str[] = sc.nextLine().split(" ");
		int nums[] = new int[str.length];
		// 放入整型数组
		for(int i=0; i<str.length; i++){
			nums[i] = Integer.parseInt(String.valueOf(str[i]));
//			System.out.println(str[i]);
		}
		
		getResult(nums);	
	}
	
	static public void getResult(int num[]){
		int start= 0;	// 连续数字的开始下标
		int max = 0;    // 记录连续数字的最大个数
		int temp= 0 ;	// temp加载每个数组元素
		int next= 0;	// temp的下一个元素
		int count = 1; 	
		
		for(int i = 1; i <num.length; i++){	// i为下标,遍历数组,注意数组不能越界
			temp = num[i-1];	
			next = num[i];
			if((next-temp) > 0){
				count ++;
			}else{
				if(max < count){
					max = count;
					start = i - count;
				}
				count = 1;
			}
		}
		max = max>count? max:count;
		for(int i = start; i<start+max; i++){
			System.out.print(num[i]+" ");
		}
		System.out.println("["+num[start]+","+max+"]");
	}
	
}

input:1 3 4 5 6 9 12 16 10 18

输出结果为: 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值