题目:
反转一个句子,要求句子中的每个单子都被反转,但单词本身不被反转
如:I am a Boy! 反转为:Boy! a am I
思路:左旋转处理
1. 将整个句子的所有字符统一反转
2. 根据空格,阶段单词,再反转每一个单词
代码:
public static String ReversalString(String StrInput){ /* char[] charTemp = StrInput.toCharArray(); int iFlagBegin = 0; int iFlagEnd = charTemp.length-1; while(iFlagBegin < iFlagEnd){ char Temp = charTemp[iFlagBegin]; charTemp[iFlagBegin] = charTemp[iFlagEnd]; charTemp[iFlagEnd] = Temp; iFlagBegin++; iFlagEnd--; } return String.valueOf(charTemp); */ String strResult = ""; for(int i =0;i<StrInput.length();i++ ){ strResult =StrInput.substring(i,i+1) + strResult; } return strResult; } public static String ReversalSentence(String Initial){ String strResult = ""; String strReversalAll = ReversalString(Initial); int iFlag = 0; for(int i = 0; i < strReversalAll.length(); i++){ if(strReversalAll.substring(i, i+1).equals(" ")){ if(i >= iFlag){ strResult += ReversalString(strReversalAll.substring(iFlag,i)) + " "; iFlag = i+1; } } if(i == strReversalAll.length() -1){ if(strReversalAll.substring(i,i+1).equals(" ")){ strResult = strResult.substring(0, strResult.length()-1); } else{ strResult += ReversalString(strReversalAll.substring(iFlag,i+1)); } } } return strResult; }
分析:注意翻转字符串的函数,用注释中的写法高效!
思路二:查找空格,直接按照单词为集合反转
public static String ReversalSentence(String Initial){ String strResult =""; int iFlag = 0; for(int i = 0; i < Initial.length(); i++){ if(i == Initial.length() -1){ strResult = Initial.substring(iFlag,i+1) + " " + strResult ; } if(Initial.substring(i, i+1).equals(" ")){ if(i >= iFlag){ if(iFlag == 0){ strResult = Initial.substring(iFlag,i) + strResult; }else{ strResult = Initial.substring(iFlag,i) + " " + strResult; } iFlag = i+1; } } } return strResult; }