剑指offer(题四)
来源:互联网 发布:php单选框默认选中 编辑:程序博客网 时间:2024/05/11 17:02
题意:将一个字符串中所有的空格替换成指定的字符串。
思路:先遍历字符串,计算有多少空格,再计算将该字符串中空格替换了指定字符串后,替换后的长度是多大。初始化一个长度为替换后长度的数组,设定两个游标,index1指向替换后数组的末尾,index2指向替换前字符串的末尾,从后往前遍历,若index2指定的字符为空格,则在index1指定的位置加上待替换的字符串,否则则将字符复制至index1位置。
代码:
package MianShiTi_4;public class MianShiTi_4 { public static int countSpace(String newstring){ int count =0; for(int i = 0; i< newstring.length() ; i++){ if(newstring.charAt(i) == ' '){ count++; } } return count; } public static int calLength(String newstring) { int length = 0; int spaceCount = 0; spaceCount = countSpace(newstring); length = newstring.length() + spaceCount*2; return length; } public String replaceAllSpace(String newString){ String s1; int newlength = calLength(newString); int originalLength = newString.length(); char []tempArray = new char[newlength]; System.arraycopy(newString.toCharArray(), 0, tempArray, 0, newString.toCharArray().length); int indexOfString = originalLength - 1; int indexOfNewString = newlength - 1; while (indexOfString >=0 && indexOfString != indexOfNewString) { if(newString.charAt(indexOfString) == ' '){ tempArray[indexOfNewString--] = '0'; tempArray[indexOfNewString--] = '2'; tempArray[indexOfNewString--] = '%'; }else{ tempArray[indexOfNewString-- ] = tempArray[indexOfString]; } indexOfString --; } s1 =new String(tempArray); return s1; } public static void main(String[] args) { String string = "I am ok"; MianShiTi_4 test = new MianShiTi_4(); int count1 = test.countSpace(string); int count2 = test.calLength(string); String s2; s2 = test.replaceAllSpace(string); System.out.println(s2); //System.out.println(count1+" "+count2); }}
0 0
- 剑指offer(题四)
- 剑指offer题四
- 剑指offer(四)
- JavaScript--《剑指offer》-题四
- 《剑指Offer》做题总结(四)
- 剑指offer之编程(四)
- 剑指offer经典编程(四)
- 剑指offer习题JAVA实现(四)
- 剑指offer 练习四(Java版)
- 剑指offer在线编程(四)
- 剑指offer(四)重建二叉树
- 剑指Offer编程整理(四)
- 剑指Offer(四)重建二叉树
- 剑指offer 四
- (四)剑指offer之重建二叉树
- 剑指Offer题目JAVA版思路与代码(四)
- 剑指offer(四)之替换空格
- 剑指Offer----面试题四:替换空格
- 3DMAX正常动画导入U3D后局部扭曲
- PAT A1094. The Largest Generation (25)
- 什么是DQL,DML,DDL,DCL
- java实现万年历
- MFC中通过按钮实现选择图片
- 剑指offer(题四)
- ubuntu配置java运行环境
- 杭电 hdu 2018. 母牛的故事
- Eclipse使用总结
- D. Cloud of Hashtags
- C++构造函数、析构函数必须要给成公有的吗?
- leetcode 70. Climbing Stairs
- 又见GCD
- 认清Android框架 MVC,MVP和MVVM