Title: Unix style to give an absolute file path, you need to simplify it. Or in other words, to convert it to the path specification. In Unix-style file system, a dot represents the current directory itself (.); In addition, two dots (...) indicates a directory to the (parent directory,); both of which may be composed of a relatively complex path section. For more information, see: Absolute path vs Linux / Unix is a relative path. Please note that the specification must always return to the path with a slash / at the beginning, and must have only one directory name between two slashes /. Finally, a directory name (if there is) not end with a /. In addition, the specification represents the shortest path must be an absolute path string.
A thought: think of the significant figures of the 65th title issues, in order to practice exercises that questions of method, I chose the way the state set. I think that even the name of the directory can also contain points (black question mark face ???), when this point can leave, when not to have studied for a long time. . . . Finally, when I am almost exhausted before. . . .
classSolution{publicintmake(char c){switch(c){case'.':return0;case'/':return1;default:return2;}}public String simplifyPath(String path){
String res ="";char[] ans =newchar[path.length()];
ans[0]='/';int state =0;int j =1;int[][] transfer =newint[][]{{1,0,2},{3,0,2},{1,0,2},{2,0,2}};char[] ss = path.toCharArray();for(int i=1;i<ss.length;i++){int id =make(ss[i]);int stateNew=transfer[state][id];if(state==0){if(id==0){
ans[j++]='.';}elseif(id==2){
ans[j++]=ss[i];}}elseif(state==1){if(id==0){
ans[j++]='.';}elseif(id==1){if(ans[j-2]=='/'){
j=j-1;}elseif(i!=ss.length-1){
ans[j++]='/';}}elseif(id==2){
ans[j++]=ss[i];}}elseif(state==2){if(id==0){
ans[j++]='.';}elseif(id==1&& i!=ss.length-1){
ans[j++]='/';}elseif(id==2){
ans[j++]=ss[i];}}elseif(state==3){if(id==0){
ans[j++]='.';}elseif(id==1){if(j>4){
j=j-4;while(j>0&& ans[j]!='/'){
j--;}
j++;}else{
j=1;}}elseif(id==2){
ans[j++]=ss[i];}}
state=stateNew;}if(state==3){if(j>4){
j=j-4;while(j>1&& ans[j]!='/'){
j--;}}else{
j=1;}}elseif(state==1){
j=j-1;}if(j>1&& ans[j-1]=='/') j--;for(int k=0;k<j;k++){
res+=ans[k];}return res;}}
Thinking two: methods are the solution to a problem in the stack to, and victims, I will not. Next time I encountered a similar problem with a stack method it again. . . .
public String simplifyPath(String path){
String[] s = path.split("/");
Stack<String> stack =newStack<>();for(int i =0; i < s.length; i++){if(!stack.isEmpty()&& s[i].equals(".."))
stack.pop();elseif(!s[i].equals("")&&!s[i].equals(".")&&!s[i].equals(".."))
stack.push(s[i]);}if(stack.isEmpty())return"/";
StringBuffer res =newStringBuffer();for(int i =0; i < stack.size(); i++){
res.append("/"+ stack.get(i));}return res.toString();}
作者:StackOverflow-
链接:https://leetcode-cn.com/problems/simplify-path/solution/java-yi-dong-yi-jie-xiao-lu-gao-by-spirit-9-18/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。