替换空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String args[]) throws Exception{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while((str=bf.readLine())!=null){
char[] ss=str.toCharArray();
StringBuffer sb = new StringBuffer();
for(int i = 0;i < ss.length; i++){
if(ss[i] == ' ')
sb.append("%20");
else
sb.append(ss[i]);
}
System.out.println(sb.toString());
}
bf.close();
}
}
class Solution {
public:
void replaceSpace(char *str,int length) {
int count=0;
for(int i=0;i<length;i++){
if(str[i]==' ')
count++;
}
for(int i=length-1;i>=0;i--){
if(str[i]!=' '){
str[i+2*count]=str[i];
}
else{
count--;
str[i+2*count]='%';
str[i+2*count+1]='2';
str[i+2*count+2]='0';
}
}
}
};
从尾到头打印链表
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> list = new ArrayList<Integer>();
while(!stack.isEmpty())
list.add(stack.pop());
return list;
}
}
class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector <int> result;
stack<int> arr;
ListNode* p=head;
while(p!=NULL)
{
arr.push(p->val);
p=p->next;
}
int len=arr.size();
for(int i=0;i<len;i++)
{
result.push_back(arr.top());
arr.pop();
}
return result;
}
};
二维数组查找
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
public class Solution {
public boolean Find(int target, int [][] array) {
if(array == null)
return false;
int rows = array.length;
int cols = array[0].length;
if(rows<=0 || cols<=0)
return false;
int row = 0;
int col = cols - 1;
while(row<rows && col>=0){
if(array[row][col] == target)
return true;
else if(array[row][col]>target)
col--;
else if(array[row][col]<target)
row++;
}
return false;
}
}
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int rowCount = array.size();
int colCount = array[0].size();
int i,j;
for(i=rowCount-1,j=0;i>=0&&j<colCount;)
{
if(target == array[i][j])
return true;
if(target < array[i][j])
{
i--;
continue;
}
if(target > array[i][j])
{
j++;
continue;
}
}
return false;
}
};