1. 程式人生 > >面試演算法題解(一)

面試演算法題解(一)

一:題目一

 題目描述:

對字串進行RLE壓縮,將相鄰的相同字元,用計數值和字元值來代替。例如:aaabccccccddeee,則可用3a1b6c2d3e來代替。

輸入描述:

輸入為a-z,A-Z的字串,且字串不為空,如aaabccccccddeee

輸出描述:

壓縮後的字串,如3a1b6c2d3e

解決思路:

首先是輸入一個字串,然後轉換為字元陣列,從第一個字元開始統計,如果和第一個相等就計數,如果不相等就立即追加字串中,然後從當前不相等的字元開始繼續執行for迴圈.最後進行統計輸出.

AC程式碼如下.

解法一:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
         Scanner cin=new Scanner(System.in);
         String str = cin.nextLine();
         StringBuilder builderZip=new StringBuilder();
         char[] chars = str.toCharArray();
         char c = chars[0];
         int count=0; 
         for(int i=0;i<chars.length;i++)
         { 
        	 if(c==chars[i]){
    		       count++;
    		 }else {
    		       builderZip.append(count+""+c);
    		       c = chars[i];
    		       count =1;
    		 }
         }
          builderZip.append(count+""+c);
        System.out.println(builderZip.toString());
	}
}

解法二:(將一個字串中的相同字元使用空串替代,計算替換後新的字串長度差,可以計算出所有相同字元的個數了.)

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
    	 Scanner cin=new Scanner(System.in);
         String str = cin.nextLine();
         int length=0;
         while(str.length()>0){
        	 String tempStr=String.valueOf(str.charAt(0));
        	 String newStr=str.replaceAll(tempStr, "");
        	 length=str.length()-newStr.length();
        	 str=newStr;
        	 System.out.print(length+""+tempStr);
        	 length=0;
         }
	}
}

二 :題目二

題目描述:

一個非空整數陣列,計算連續子陣列的最大和。如果最大的和為正數,則輸出這個數;如果最大的和為負數或0,則輸出0.

輸入描述:

3,-5,7,-2,8

輸出描述:

13

解題思路:

動態規劃直接解決,連續子陣列最大和,注意輸入的是一個數組,但是沒有指定陣列的大小,輸入字串然後進行分割進行轉換為陣列.

不使用自帶的庫函式.

就是當前所有的值的和,和接下來的值進行比較如果大於就賦值新的,如果小於那麼當前的最大值任然是這個值,繼續運算.從後往前計算.

AC程式碼如下:

import java.util.Scanner;
public class Main {
     public static void main(String[] args) {
        Scanner cin=new Scanner(System.in);
        String[] strings=cin.nextLine().split(",");
        int[] nums=new int[strings.length];
        for(int i=0;i<nums.length;i++){
            nums[i]=Integer.valueOf(strings[i]);
        }
        System.out.println(getMaxResult(nums));
     }
     public static int getMaxResult(int[] nums){
           int res,fmax;
           fmax=nums[0];
           res=fmax;
           if(nums.length==0){
               return 0;
           }
           for(int i=1;i<nums.length;i++){
               if(fmax+nums[i]>nums[i]){
                   fmax=fmax+nums[i];
               }else{
                   fmax=nums[i];
               }
               if(res<fmax){
                   res=fmax;
               }
           }
               if(res>0){
                   return res;
               }else{
                   return 0;
           }
     }
}