算法题(1)

java算法题(1)


1:【15分】 标题:字符逆序 | 时间限制:1秒 | 内存限制:32768K

将一个字符串str的内容颠倒过来,并输出。str的长度不超过100个字符。 如:输入“I am a student”,输出“tneduts a ma I”。
输入参数:
inputString:输入的字符串
返回值:
输出转换好的逆序字符串

输入描述:
输入一个字符串,可以有空格
输出描述:
输出逆序的字符串
示例1
输入
I am a student
输出
tneduts a ma I

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Main {
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        String words = null;
        while((words = br.readLine()) != null){
          //  System.out.println( 7ms 9212kb
          //      new  StringBuilder(words).reverse().toString());
          //7 ms 9232kb
            char [] wws = words.toCharArray();
            int len = words.length();
            for(int i= len - 1; i>=0; i--){
                System.out.print(wws[i]);
            }
             System.out.println();
        }

        //Scanner scan = new Scanner(System.in);
        // 24ms 10922kb 吃内存
        //while(scan.hasNext()){} words = scan.nextLine();
    }
}

2:【15分】 标题:句子逆序 | 时间限制:1秒 | 内存限制:32768K

将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符
接口说明
/**
 * 反转句子
 * 
 * @param sentence 原句子
 * @return 反转后的句子
 */
public String reverse(String sentence);

输入描述:
将一个英文语句以单词为单位逆序排放。
输出描述:
得到逆序的句子
示例1
输入
I am a boy
输出
boy a am I

public class Main {
    public static void main (String[] args) throws IOException{
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        String word = null;
        while((word = br.readLine()) != null ){
            String[] words =  word.split(" ");
            StringBuilder sb = new StringBuilder();
            int len = words.length;
            //1:倒序追加
            for(int i = len -1 ; i > 0;i--){
                //sb.append(words[i] + " ");
                System.out.print(words[i] + " ");//13ms
            }
            //2:清零插入 10ms 
            for(int i = 0 ; i < len;i++){
                sb.insert(0,words[i] + " ");
            }
            //3:转为字符数组插入 10ms  9196kb
            int index = 0;
            char[]  ss = word.toCharArray();
            len = ss.length;
            for(int i = 0 ; i < len;i++){
               if (ss[i] == ' ')  {
                   sb.insert(0,ss[i]);
                   index = 0;
               } else {
                 sb.insert(index,ss[i]);
                 index ++;
               }
            }

            //System.out.println(words[0]);
            System.out.println(sb.toString().trim()); //8 ms
           // Character.isLetter();
        }
    }
}

3:【15分】 标题:空格替换 | 时间限制:3秒 | 内存限制:32768K

请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。
给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。
测试样例:
"Mr John Smith”,13
返回:"Mr%20John%20Smith"
”Hello World”,12
返回:”Hello%20%20World”

public class Solution {
    public String replaceSpace(StringBuffer str) {
      if (str == null || str.length() == 0 ) return "";
      char [] strss = str.toString().toCharArray();
      //str.delete(0,strss.length); //追加和插入

      int i=0;
      for(int j = 0; j < strss.length; j++ ){
          if (strss[j] == ' '){
              //str.append("%20"); //追加 12ms 9836kb
              str.deleteCharAt(i); //插入 13 ms 9756kb
              str.insert(i,"%20");
              //str.replace(i,i+1,"%20"); //替换 14ms 10036kb
              i = i+3;
          } else {
              //str.append(strss[j]);
              i++;
          }
      }
      return str.toString();
    }
}

4:【15分】 标题:删除公共字符 | 时间限制:1秒 | 内存限制:32768K

输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
输入描述:
每个测试输入包含2个字符串
输出描述:
输出删除后的字符串
示例1
输入
They are students. 
aeiou
输出
Thy r stdnts.

    public static void main (String[] sasa) throws IOException{
        BufferedReader br =new BufferedReader(
            new InputStreamReader(System.in));
        String temp = null;
        while((temp = br.readLine()) != null){
            String cons = br.readLine();
            // System.out.println(temp.replaceAll("[" + cons + "]","")); 8ms 9472kb
            char[] css = temp.toCharArray();
            for(int i =0 ; i< css.length ; i++){
                if(!cons.contains("" + css[i])) System.out.print(css[i]); //7ms 9052kb
            }
            System.out.println();
        }
    }

5:【15分】 标题:字符串的旋转 | 时间限制:3秒 | 内存限制:32768K

对于一个字符串,和字符串中的某一位置,请设计一个算法,将包括i位置在内的左侧部分移动到右边,将右侧部分移动到左边。
给定字符串A和它的长度n以及特定位置p,请返回旋转后的结果。
测试样例:
"ABCDEFGH",8,4
返回:"FGHABCDE"



6;【15分】 标题:字符集合 | 时间限制:1秒 | 内存限制:32768K
输入一个字符串,求出该字符串包含的字符集合
输入描述:
每组数据输入一个字符串,字符串最大长度为100,且只包含字母,不可能为空串,区分大小写。
输出描述:
每组数据一行,按字符串原有的字符顺序,输出字符集合,即重复出现并靠后的字母不输出。
示例1
输入
abcqweracb
输出
abcqwer

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        String words = null;
        while((words = br.readLine()) != null){
            char [] chs = words.toCharArray();
            //int[] chsc = new  int[256];
            int len = words.length();
            StringBuilder sb = new StringBuilder("");
            Set<Character> chsset = new HashSet<Character>();
            Map<Character,Integer> chsmap = new HashMap<Character,Integer>();
            for(int i=0; i < len ; i++){
                //1: sb
                if (!sb.toString().contains("" + chs[i])){
                    sb.append(chs[i]);
                }
                //2: set
                if(chsset.add(chs[i])){
                 // System.out.print(chs[i]);
                  sb.append(chs[i]);
                }

                //3:map
                if(!chsmap.containsKey(chs[i])){
                    chsmap.put(chs[i],0);
                    //System.out.print(chs[i]);
                    sb.append(chs[i]);
                }

            }
             //System.out.println();
             System.out.println(sb.toString());
        }
    }

7:【15分】 标题:寻找第K大 | 时间限制:3秒 | 内存限制:32768K

有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
测试样例:
[1,3,5,2,2],5,3
返回:2

public class Solution {
    public int findKth(int[] a, int n, int K) {
       
        //int value = K;
        //int countcc = n;
        //Arrays.sort(a);
        //return a[countcc -value];
        return findK(a, 0,a.length-1,K);
    }
    
    public int findK(int[] arr, int leftpos,int rightpos,int  k) {
        int indexpos = position(arr,leftpos,rightpos);
        
        if(k == indexpos + 1 - leftpos){
            return arr[indexpos];
        }else if (k > indexpos + 1 - leftpos){
            return findK(arr,indexpos + 1,rightpos,k - 1 - indexpos + leftpos);
        }else
            return findK(arr, leftpos, indexpos - 1, k);
    }
    
    public int position(int[] arr, int startpos,int endpos){
        int key = arr[startpos];

        while(startpos < endpos){
            while(startpos < endpos && key >= arr[endpos]) 
                endpos --;
            arr[startpos] = arr[endpos];
            while(startpos < endpos && key <= arr[startpos]) 
                startpos ++;
            arr[endpos] = arr[startpos];
        }

        arr[startpos] = key;
        return startpos;
    }
    
}

8:【15分】 标题:统计大写字母个数 | 时间限制:1秒 | 内存限制:32768K

找出给定字符串中大写字符(即'A'-'Z')的个数
接口说明
原型:int CalcCapital(String str);
返回值:int
注意:测试数据需要考虑循环输入
输入描述:
输入一个String数据
输出描述:
输出string中大写字母的个数
示例1
输入
add123#$%#%#O
输出
1

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        String words = null;
        while((words = br.readLine()) != null){
            String regx = "[^A-Z]+";// [^\w\d\D\W+]
            // 9ms 9300kb
            System.out.println(words.replaceAll("[^A-Z]+","").length());
            char [] wws = words.toCharArray();
            int len = words.length();
            int c =0;
            for(int i= 0; i< len; i++){
                //7MS 9264KB
               if(wws[i] >= 'A' && wws[i] <= 'Z'){
                   c ++;//isUpperCase 大写Character.isUpperCase(wws[i])
               }else if (Character.isLowerCase(wws[i])){
                   //isLowerCase 小写
               }else if (Character.isLetter(wws[i])){
                   //isLetter 字母 isLetterOrDigit
               }else if (Character.isWhitespace(wws[i])){
                   //isSpaceChar()|isSpace 空白
                   //isWhitespace 空格和空白
               }else if (Character.isDigit(wws[i])){
                   //数字
               }else {
                   //其他字符
               }
            }
            System.out.println(c);
        }
    }

9:【15分】 标题:查找输入整数二进制中1的个数 | 时间限制:1秒 | 内存限制:32768K

请实现如下接口
     public   static   int  findNumberOf1( int num)
    {
         /*  请实现  */
         return  0;
    } 譬如:输入5 ,5的二进制为101,输出2
 
涉及知识点:
输入描述:
输入一个整数
输出描述:
计算整数二进制中1的个数
示例1
输入
5
输出
2

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Main {
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        String words = null;
        while((words = br.readLine()) != null){
            int c =0;
            int n = Integer.parseInt(words);
            //1: 转为Integer.toBinaryString 9ms 9332kb
            //c = Integer.toBinaryString(n).replaceAll("0","").length();
            //2: &运算 10ms 9312kb
            while(n> 0){
                c += n&1;
                n >>>= 1;
            }
            //3:转toCharArray,判断‘1’个数 7ms 9268kb
            char[] chs = Integer.toBinaryString(n).toCharArray();
            for(char ch : chs){
                if ( ch == '1') c ++;
            }
            System.out.println(c);
        }
    }
}

10:【15分】 标题:字符串中找出连续最长的数字串 | 时间限制:1秒 | 内存限制:32768K

读入一个字符串str,输出字符串str中的连续最长的数字串
输入描述:
个测试输入包含1个测试用例,一个字符串str,长度不超过255。
输出描述:
在一行内输出str中里连续最长的数字串。
示例1
输入
abcd12345ed125ss123456789
输出
123456789

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Main {
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        String words = null;
        while((words = br.readLine()) != null){
            int max = -1;
            //1: 使用正则split 8ms 9336kb
            String [] ss = words.split("[\D]+"); //"[^0-9]+"
            for(String ch : ss){
                if ( ch.length() > max ) max = ch.length() ;
            }
            for(String ch : ss){
                if ( ch.length() == max ) System.out.print(ch);
            }

            //2: 转toCharArray() 8ms 9224kb
            char [] chss = words.toCharArray();
            int c = 0,len = words.length();
            StringBuilder sb = new StringBuilder("");

            for( int i = 0; i <len ; i++){
               char chr = chss[i];
               if (Character.isDigit(chr)){ 
                   c ++;
               }
               else {
                  if (c >0 && c >= max) {
                     if (c > max) {
                        max = c; 
                        sb.delete(0,sb.length());
                     }
                     sb.append(words.substring(i - max,i));
                  }
                  c = 0;
               }
            }
            if (c >= max) {
                if (c > max) {
                    max = c;
                    sb.delete(0,sb.length());
                }
                sb.append(words.substring(len - c,len));
            }

            System.out.println(sb.toString() +"," + max);
        }
    }
}

11:【15分】 标题:约瑟夫问题I | 时间限制:3秒 | 内存限制:32768K

约瑟夫问题是一个非常著名的趣题,即由n个人坐成一圈,按顺时针由1开始给他们编号。然后由第一个人开始报数,数到m的人出局。现在需要求的是最后一个出局的人的编号。
给定两个int n和m,代表游戏的人数。请返回最后一个出局的人的编号。保证n和m小于等于1000。
测试样例:
5 3
返回:4

    public int getResult(int n, int m) {
        if (n < 0 || m < 0) {
            return -1;
        }
        int last = 0;
        for(int i=2;i<=n;++i){
            last = (last+m)%i;
        }
        // 因为实际编号为(1~n)
        return (last+1);
    }

12:【15分】 标题:上台阶 | 时间限制:3秒 | 内存限制:32768K

	,刚开始时你在第一级,若每次只能跨上一级或者二级,要走上n级,共有多少走法?注:规定从一级到一级有0种走法。

给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100。为了防止溢出,请返回结果Mod 1000000007的值。
测试样例:
3
返回:2

    int countWays(int n) {
        // write code here
        if(n==1) return 1;
        int f0=1;
        int f1=1;
        for(int i=3;i<=n;i++)
        {
            int tmp=f1;
            f1=(f1+f0)%(1000000007);
            f0=tmp;
        }
        return f1;
    }
    //递归
   public static int f(int n){
    if(n<=2) return n;
    int x = f(n-1)+f(n-2);
    return x;
   }
   //迭代递推
   public static int f(int n){
    if(n<=2) return n;
    if first=1,second=2;
    int third=0;
    for(int i=3;i<=n;i++){
        third = first+second;
        first = second;
        second = third;
    }
    return third;
   }
   //动态规划
   public static int[] A = new int[100];
   public static int f(int n){
       if(n<=2){
           A[n] = n;
       }
       if(A[n]>0){
           return A[n];
       } else {
           A[n] = f(n-1)+f(n-2);
           return A[n];
       }
   }

原文地址:https://www.cnblogs.com/yiyangyu/p/suanfa001.html