三道简单算法题

本文介绍了三种字符串处理技巧:一是寻找两个字符串的最大公共子串;二是生成杨辉三角形;三是比较两个字符串数组,将不在第一个数组中出现的元素插入到预留的位置。

 

第一题
/*
 求两个字符串的最大公共子串
 String s1 = "abcdefghigj";
 String s2 = "xyzabcdeigj";
 则输出abcde
*/

第二题
/*
输出杨辉三角形
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
*/

第三题
/*
String[] a = {"a","b","c","d","e","f","g","h","i","j","",""};
String[] b = {"f","a","c","f","e","k","l","y","p","o"};

如果b里面的数据在a里面没有,则把没有的数据放到""里面,超过的话,则报"已经满了,无法插入"~~
*/

解析:
第一题:
public class first
{
  public String search(String s1,String s2)
  {
  String max = "";
  for(int i=0; i<s1.length(); i++)
  {
    for(int j=i; j<s1.length(); j++)
    {
      String sub = s1.substring(i,j);
      if((s2.indexOf(sub)!=-1)&&sub.length()>max.length())
      {
        max = sub;
      }
    }
  } 
  return max;
  }
 
  public static void main(String[] args)
  {
    String s1 = "abcdefghigj";
    String s2 = "xyzabcdefigj";
    String output = new first().search(s1,s2);
    System.out.println(output);
  }
}

第二题:
public class second
{
  public static int[] general(int[] data)
  {
    int[] fanhui = new int[data.length+1]; 
    fanhui[0] = data[0];
    for(int i=1,j=1; j<data.length; i++,j++)
    {
      fanhui[i] = data[j-1] + data[j];
    }         
    fanhui[fanhui.length-1] = data[data.length-1];
    for(int k=0; k<fanhui.length; k++)
    {
      System.out.print(fanhui[k] + "/t");
    }
    System.out.print("/n");
    return fanhui;
  }
  public static void main(String[] args)
  {
    int times = 5;
    int[] chushizhi = {1};
    System.out.println(chushizhi[0]);
    for(int i=0; i<times; i++)
    {
    chushizhi = second.general(chushizhi);   
    }
  }
}

第三题:

import java.util.ArrayList ;

public class Third
{
public static void main(String[] args)
{
    String[] a = {"a","b","c","d","e","f","g","h","i","j","k","",""};
    String[] b ={"f","a","c","f","e","k","l"};
    Third third = new Third();
    third.compareAndReplace(a,b);
    StringBuffer output = new StringBuffer();
    for(int i=0; i<a.length; i++)
    output.append(a[i]); 
    System.out.println("a已变成" + output.toString());
  }
 public void compareAndReplace(String[] a,String[] b)
 {
   for(int i=0; i<b.length; i++)
   {
      outer:
     for(int j=0; j<a.length; j++)
     {
       if(b[i].equals(a[j]))
       break outer;
       if(j==a.length-1)
       {
       if(findFirstSpace(a)!=-1)
       {
         a[findFirstSpace(a)] = b[i];
       }
       else
       {
         System.out.println("已经满了,无法插入" + b[i]);
       }      
     }
   }
 }
 }
 
 public int findFirstSpace(String[] arg)
 {
   for(int m=0; m<arg.length; m++)
   {
     if(arg[m].equals(""))
     return m;    
   }
   return -1;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值