剑指offer-(第一天)

来源:互联网 发布:高级软件测试面试题 编辑:程序博客网 时间:2024/06/06 01:55

1、替换空格

/*
*题目:请实现一个函数,把字符串中的每个空格替换成“%20”
*思路:先统计出该字符串中空格的数目,然后对字符数组进行扩容,然后再将字符依次写入数组
*/



public static void ReplaceSpace(char[] string,int length){
  //string为原字符串数组,length为该数组最大能够容纳字符的数目
  if(string==null||length<=0) return;
  int originalLength=0;
  int numOfSpace=0;
  int i=0;
  while(string[i]!='\0'){
    originalLength++;
    if(string[i]==' ')
    numOfSpace++;
    i++;
  }


  int newLength=originalLength+numOfSpace*2;
  if(newLength>length)  return;
  int indexOfOriginal=originalLength;
  int indexOfNew=newLength;
  while(indexOfOriginal>=0&&indexOfOriginal>indexOfNew){
    if(string[indexOfOriginal]!=' '){
      string[indexOfNew--]=string[originalLength];
    }
    else{
      string[indexOfNew--]='%';
      string[indexOfNew--]='2';
      string[indexOfNew--]='0';
    }
    indexOfOriginal--;
  }
}


2、从尾到头打印链表

/*
*题目:从尾到头打印链表
*思路:使用栈结构实现,依次将链表中元素压入栈中,然后依次出栈即可;或使用递归方式实现
*/


public static void PrintLinkedList(ListNode head){
  ListNode pHead=head;
  Stack<ListNode> stack=new Stack<ListNode>();
  while(pHead!=null){
    stack.push(pHead);
    pHead=pHead.next;
  }
  while(!stack.empty()){
    pHead=stack.top();
    System.out.print(list.value+",");
    stack.pop();
  }
  System.out.println();
}


//递归实现


public static void PrintLinkedList(ListNode head){
  if(head!=null){
    if(head.next!=null){
      PrintLinkedList(head.next);
    }
    System.out.print(head.value+",");
  }
  System.out.println();
}

1 0
原创粉丝点击