华为面试题

1.算法JAVA实现:输入一个字符串,输出该字符串中的连续相同最长的子字符串,如果有多个长度相同的子串,则输出ascii码最小的那个。

测试用例:

例如输入aaaaavvvvvvvvvcccc

输出:vvvvvvvvv;

输入asdczxcweqwe,输出a;

 1 import java.util.Scanner;
 2  
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner scanner =new Scanner(System.in);
 6         while (scanner.hasNext()) {
 7             String line =scanner.nextLine();
 8             char[] chars=line.toCharArray();
 9             int length=chars.length;
10             int maxlength=0;
11             //结果
12             String maxSubstring="";
13             //暂存最长字符串的始末位
14             int begin=0,end=1;
15             //暂存最长字符,用来比较ascii码
16             char c=' ';
17             for (int i=0;i<length;i++){
18                 if (i==0){
19                     c=chars[0];
20                     maxSubstring=c+"";
21                     maxlength=1;
22                 }else{
23                     if (chars[i]==chars[i-1]){
24                         if (end<length-1){
25                             end++;
26                         }else{
27                             end=length;
28                         }
29                         if (end-begin>maxlength){
30                             maxlength=end-begin;
31                             c=chars[i];
32                             maxSubstring=line.substring(begin,end);
33                         }else if(end-begin==maxlength){
34                             //选择ascii码较小的那个子串
35                             if (chars[i]<c){
36                                 c=chars[i];
37                                 maxSubstring=line.substring(begin,end);
38                                 maxlength=end-begin;
39                             }
40                         }
41                         //没有连续子串的情况,取ascii码小的那个
42                     }else if(chars[i]!=chars[i-1]&&maxlength==1&&chars[i]<c) {
43                         c=chars[i];
44                         begin=i;
45                         end =i+1;
46                         maxlength=1;
47                         maxSubstring=chars[i]+"";
48                     }else {
49                         begin=i;
50                         if (i<length-1){
51                             end =i+1;
52                         }else{
53                             end=length;
54                         }
55                     }
56                 }
57             }
58             System.out.print(maxSubstring);
59         }
60  
61     }
62 }

 

posted @ 2020-04-24 12:23  seedss  阅读(350)  评论(0编辑  收藏  举报