博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
"Coding Interview Guide" -- 字符串的统计字符串
阅读量:4610 次
发布时间:2019-06-09

本文共 1732 字,大约阅读时间需要 5 分钟。

题目

  给定一个字符串str,返回str的统计字符串

  例如,"aaabbadddffc"的统计字符串为"a_3_b_2_a_1_d_3_f_2_c_1"

 

1 public String count(String str) 2 { 3     if(str == null || str.equals("")) 4     { 5         return ""; 6     } 7  8     char[] chas = str.toCharArray(); 9     String cstr = String.valueOf(chas[0]);10     int num = 1;11     for(int i = 1; i < chas.length; i++)12     {13         if(chas[i] != chas[i - 1])14         {15             cstr = concat(cstr, String.valueOf(num), String.valueOf(chas[i]));16             num = 1;17         }18         else19         {20             num++;21         }22     }23         24     return concat(cstr, String.valueOf(num), "");25 }26 27 28 public String concat(String s1, String s2, String s3)29 {30     return s1 + "_" + s2 + (s3.equals("") ? s3 : "_" + s3);31 }

 

 

题目

  给定一个字符串的统计字符串cstr,再给定一个整数index,返回cstr所代表的原始字符串上的第index个字符

  例如,"a_1_b_100"所代表的原始字符串上第0个字符是'a',第50个字符是'b'

 

1 public char getCharAt(String str, int index) 2 { 3     if(str == null || str.equals("") || index < 0) 4     { 5         return 0; 6     } 7  8     char[] chas = str.toCharArray(); 9     boolean stage = true;10     char cur = 0;11     int sum = 0;12     int num = 0;13     for(int i = 0; i < chas.length; i++)14     {15         if(chas[i] == '_')16         {17             stage = !stage;18         }19         else if(stage)20         {21             sum += num;22             if(sum > index)23             {24                 return cur;25             }26             num = 0;27             cur = chas[i];28         }29         else30         {31             num = num * 10 + chas[i] - '0';32         }33     }34     return sum + num > index ? cur : 0;35 }36 37

 

来源:左程云老师《程序员代码面试指南》

转载于:https://www.cnblogs.com/latup/p/10943819.html

你可能感兴趣的文章
DOC常用命令(转)
查看>>
php写一个判断是否有cookie的脚本
查看>>
Mac配置Fiddler抓包工具
查看>>
转:Java并发集合
查看>>
Word截图PNG,并压缩图片大小
查看>>
Python项目对接CAS方案
查看>>
mysql产生随机数
查看>>
编程风格
查看>>
熟悉常用的Linux命令
查看>>
易之 - 我是个大师(2014年3月6日)
查看>>
Delphi中窗体的事件
查看>>
file_get_contents()获取https出现这个错误Unable to find the wrapper “https” – did
查看>>
Error:Syntax error: redirection unexpected
查看>>
linux vi编辑器
查看>>
js树形结构-----(BST)二叉树增删查
查看>>
contract
查看>>
FJUT ACM 1899 Largest Rectangle in a Histogram
查看>>
如何删除xcode项目中不再使用的图片资源
查看>>
编写用例文档
查看>>
解决WPF两个图片控件显示相同图片因线程占用,其中一个显示不全的问题
查看>>